<template>
  <div class="index" :class="{ 'fullscreen-mode': isFullscreen }">
    <div class="left-sidebar" :class="{ 'hidden': isFullscreen }">
      <!-- 左侧菜单内容 -->
    </div>
    <div class="dashboard">
      <!-- 右上角时间更新信息和全屏按钮 -->
      <div v-if="dataStatus.lastUpdate" class="data-status">
        <!--                <span>最后更新: {{ dataStatus.lastUpdate }}</span>-->
        <!--                <span v-if="dataStatus.updating" class="updating-dot"></span>-->
        <div class="fullscreen-btn" @click="toggleFullscreen">
          <i :class="isFullscreen ? 'el-icon-close' : 'el-icon-full-screen'"></i>
        </div>
      </div>

      <!-- 顶部标题区 -->
      <div class="header">
        <div class="title-section">
          <h1>汽车厂主轴监测平台</h1>
        </div>
      </div>

      <!-- 主要内容区 -->
      <div class="content">
        <!-- 左侧统计和监测模块 -->
        <div class="left-module">
          <div class="stat-card">
            <div class="chart-title">
              设备使用率统计
            </div>
            <div class="stat-content">
              <div class="circle-progress" id="deviceStatusChart"></div>
            </div>
          </div>
          <div class="usage-chart">
            <div class="chart-title">
              设备使用率曲线
            </div>
            <div id="usageChart" class="chart"></div>
          </div>
          <div class="monitor-log">
            <div class="chart-title">
              监测记录
            </div>
            <div class="log-list">
              <transition-group name="log-slide" tag="div" class="log-items-wrapper">
                <div v-for="log in monitorLogs" :key="log.deviceName" class="log-item"
                     :class="[
                                         getStatusClass(log.type), // 这为基础样式提供了类（例如，如果我们想要不同的默认背景）
                                         { 'new-alarm-highlight': log.isNewAlarm } // 为新告警添加特定高亮
                                     ]">
                  <div class="status-tag"
                       :class="[getStatusClass(log.type), { 'status-change-animate': latheNamesToAnimate.has(log.deviceName) }]">
                    {{ log.type }}
                  </div>
                  <div class="log-content">
                    <span class="device-name">{{ log.deviceName }}</span>
                  </div>
                  <div class="log-time">{{ log.time }}</div>
                  <!-- AI 问询按钮，仅在故障时显示 -->
                  <div v-if="log.type === '故障'" class="ai-log-btn" @click.stop="inquiryFromLog(log)">
                    <i class="el-icon-service"></i>
                  </div>
                </div>
              </transition-group>
            </div>
          </div>
        </div>

        <!-- 中间设备网格模块 -->
        <div class="center-module">
          <!-- 添加车间切换按钮组 -->
          <div class="workshop-buttons">
            <div class="switch-buttons">
              <button
                v-for="(workshop, index) in workshops"
                :key="index"
                class="switch-btn"
                :class="{ active: currentWorkshop === workshop.id }"
                @click="switchWorkshop(workshop.id)"
              >
                {{ workshop.name }}
              </button>
            </div>
          </div>

          <!-- 设备网格 -->
          <div class="device-grid">
            <div v-for="latheName in uniqueLatheNames" :key="latheName" class="device-item"
                 :class="[
                                getLatheNameStatus(latheName),
                                { active: currentDevice.latheName === latheName },
                                { 'auto-hover-active': autoHoverDeviceName === latheName } // 新增绑定
                            ]"
                 @click="selectLatheNameDevice(latheName)"
                 @mouseenter="handleDeviceItemMouseEnter()"
                 @mouseleave="handleDeviceItemMouseLeave()">
              <div class="device-icon">
                <img :src="getLatheNameIcon(latheName)" alt="device icon" @error="handleImageError">
              </div>
              <!-- 添加悬浮提示框 -->
              <div class="device-tooltip"
                   :class="[getStatusClass(getLatheNameStatus(latheName)), { 'auto-tooltip-active': autoHoverDeviceName === latheName }]">
                <span>{{ latheName }}</span>
                <span class="status-line">
                                    状态: {{ getLatheNameStatus(latheName) }}
                                </span>
                <span v-if="getLatheNameStatus(latheName) === '故障'" class="ai-tooltip-btn" @click.stop="inquiryFromLog({ deviceName: latheName })">
                                    <i class="el-icon-service"></i>
                                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 右上评分和运行率模块 -->
        <div class="right-top-module">
          <div class="health-score">
            <div class="chart-title">
              设备健康评分
            </div>
            <div class="score-content">
              <div class="score-circle" id="healthScoreChart"></div>
              <!-- <div class="score-details">
                                <div v-for="(detail, index) in healthScore.details" :key="index" class="detail-item">
                                    {{ detail }}
                                </div>
                            </div> -->
            </div>
          </div>
          <div class="running-rate">
            <div class="chart-title">设备稳定运行率</div>
            <div id="runningRateChart" class="chart"></div>
          </div>
        </div>

        <!-- 右下加速度模块 -->
        <div class="right-bottom-module">
          <div class="acceleration-chart">
            <div class="chart-title">
              <div class="title-text">{{currentDevice.latheName}}加速度数据</div>
              <div class="chart-controls">
                <!-- 状态标签 -->
                <div class="status-tag" :class="getStatusClass(getLatheNameStatus(currentDevice.latheName))">
                  {{ getLatheNameStatus(currentDevice.latheName) }}
                </div>

                <!-- 安装位置下拉选择器 - 仅在设备有数据且有位置信息时显示 -->
                <div class="position-dropdown" v-if="hasDeviceData(currentDevice.id) && devicePositions.length > 0">
                  <el-dropdown @command="switchPosition" trigger="click">
                                        <span class="el-dropdown-link">
                                            {{ currentPosition || '选择安装位置' }} <i class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                    <el-dropdown-menu >
                      <el-dropdown-item
                        v-for="(position, index) in devicePositions"
                        :key="'pos-'+index"
                        :command="position"
                        :class="{ 'active-position': currentPosition === position }">
                        {{ position }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>

                <!-- 类型切换按钮组 - 始终显示 -->
                <div class="switch-buttons type-buttons">
                  <button class="switch-btn" :class="{ active: accelerationType === 'rms' }"
                          @click="switchAccelerationType('rms')">
                    均方根
                  </button>
                  <button class="switch-btn" :class="{ active: accelerationType === 'peak' }"
                          @click="switchAccelerationType('peak')">
                    峰值
                  </button>
                </div>
                <!-- 一键问询按钮 -->
                <div class="switch-buttons ai-buttons">
                  <button class="switch-btn" @click="goToInquiry" :disabled="!currentDevice.id">
                    问询AI
                  </button>
                </div>
              </div>
            </div>
            <div v-if="hasDeviceData(currentDevice.id)" class="chart-container">
              <div id="accelerationChart" style="height: 100%; width: 100%;"></div>
            </div>
            <div v-else class="no-data-container">
              <div class="no-data-message">
                <i class="el-icon-warning-outline"></i>
                <p>该设备处于【{{ getLatheNameStatus(currentDevice.latheName) }}】状态，暂无数据</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getStatus,getAccelerationData } from '../../../api/real/detect'
import { getWaveformDataByrangeTime } from '../../../api/real/waveform'

import 'echarts-liquidfill'


export default {
  name: "Index",
  data() {
    return {
      usageChart: null,        // 使用率曲线
      accelerationChart: null, // 加速度数据
      runningRateChart: null,  // 设备稳定运行率
      deviceStatusMap: {
        '正常': 'normal',
        '故障': 'warning',
        '待机': 'waiting',
        '离线': 'offline'
      },
      deviceStatusData: [],
      deviceStatus: {
        normalCount: 0,
        normalRate: 0,
        warningCount: 0,
        warningRate: 0,
        waitingCount: 0,
        waitingRate: 0,
        offlineCount: 0,
        offlineRate: 0
      },
      totalDevices: 35,
      DevicesId: [30096429, 30096457, 30096464,30096424, 30096546, 20031108, 30096407, 30096408, 30096409, 30096410, 30096411, 30096412, 30096413, 30096414, 30096415, 30096416, 30096417, 30096418, 30096419, 30096420, 30096421, 30096422, 30096423, 30096437, 30096438, 30096439, 30096440, 30096441, 30096442, 30096443, 30096444, 30096445, 30096446, 30096447,30096448,30096570],
      runningRates: [85, 82, 88, 84, 86, 83, 87],  // 运行率数据
      monitorLogs: [],
      loading: false,
      timer: null,
      accelerationData: {
        rms: {
          x: Array(15).fill(0),  // 修改为15个点，对应75分钟
          y: Array(15).fill(0),
          z: Array(15).fill(0)
        },
        peak: {
          x: Array(15).fill(0),
          y: Array(15).fill(0),
          z: Array(15).fill(0)
        }
      },
      updateInterval: 2000,
      dataUpdateTimer: null,
      dataStatus: {
        updating: false,
        lastUpdate: '',
        errorCount: 0
      },
      previousData: null, // 用于存储上一次的数据，实现平滑过渡
      currentDevice: {
        id: 30096546,
        name: '设备 01',
        latheName: '设备', // 添加latheName属性
        peakHistory: [] // 存储历史 peak 值的数组
      },
      maxPeakPoints: 100, // 最多保存100个数据点
      timeData: Array(30).fill('').map((_, index) => {  // 30个点，每点间隔1分钟
        const time = new Date(Date.now() - (29 - index) * 60000); // 每点间隔1分钟(60,000毫秒)
        return time.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
        });
      }),
      healthScore: {
        score: 100,
        details: [],
        status: 'normal'
      },
      timePoints: ['0', '2', '4', '6', '10', '12', '14', '16', '18', '20', '22', '24'],
      isFullscreen: false,
      fullscreenHandler: null,
      liquidChart: null,
      accelerationType: 'rms', // 新增：加速度类型
      accelerationHistory: [], // 存储加速度历史数据
      maxHistoryPoints: 30,   // 显示30个数据点
      accelerationTimer: null, // 添加定时器引用
      deviceStatusChart: null, // 新增设备状态环形图实例
      workshops: [
        { id: 1, name: '一期车间' },
        { id: 2, name: '二期车间' },
        { id: 3, name: '三期车间' }
      ],
      currentWorkshop: 1, // 默认选中车间一
      deviceAccelerationData: {}, // 存储每个设备的加速度数据
      devicePositions: [], // 存储设备安装位置列表
      currentPosition: '', // 当前选中的安装位置
      latheNameList: [], // 存储所有设备的latheName列表
      latheNameToDeviceMap: {}, // latheName到deviceId的映射
      uniqueLatheNames: [], // 唯一的latheName列表，用于网格显示
      monitorLogTimer: null, // 新增监测记录轮播定时器
      autoHoverDeviceName: null, // 当前自动悬浮的设备名称
      autoHoverTimer: null, // 自动悬浮定时器ID
      autoHoverInterval: 5000, // 自动悬浮间隔，例如5秒
      currentAutoHoverIndex: -1, // 当前自动悬浮的设备索引
      tooltipPositionAdjusted: false, // 标记提示框位置是否已调整
      lastHoveredWarningDevice: null, // 记录最后一个悬浮显示的故障设备
      previousLatheNameStatuses: {}, // 新增：存储设备之前的状态
      latheNamesToAnimate: new Set(), // 新增：需要播放状态变化动画的设备名集合
      newlyFaultyLatheNames: new Set(), // 新增：用于跟踪最新故障设备
      latheNameSummaries: {}, // 新增：用于存储每个latheName的聚合状态和最新收集时间
      monitorLogDisplayOffset: 0, // 新增：用于监测记录轮播的偏移量
      lastNotifiedFaults: new Set(), // 新增：已弹出 Toast 的故障设备
    }
  },
  created() {
    // 初始化设备加速度数据存储
    this.deviceAccelerationData = {};

    // 立即获取一次所有设备的加速度数据
    this.prefetchAccelerationData().then(() => {
      // 获取数据后，设置第一台设备为当前设备
      const firstLatheName = this.uniqueLatheNames[0];
      const firstDeviceId = this.latheNameToDeviceMap[firstLatheName]?.[0] || this.DevicesId[0];

      this.currentDevice = {
        id: firstDeviceId,
        name: firstLatheName || this.getDeviceName(firstDeviceId),
        latheName: firstLatheName || this.deviceAccelerationData[firstDeviceId]?.latheName || this.getDeviceName(firstDeviceId),
        putPlace: this.deviceAccelerationData[firstDeviceId]?.putPlace || '',
      };

      // 初始化图表
      this.initCharts();
      this.startAutoDeviceHover(); // 数据加载后启动设备自动悬浮
      this.loadHistoricalAccelerationData(this.currentDevice.id).then(() => {
        // Ensure chart is initialized or updated after historical data attempt
        if (this.hasDeviceData(this.currentDevice.id)) {
          this.initAccelerationChart();
        } else {
          // If no data even after history load (e.g. API error / no history and device offline)
          // still try to init chart with placeholder if not already done.
          this.initAccelerationChart();
        }
      });
    });

    // 开始数据更新循环
    this.startDataUpdate();

    // 获取设备安装位置数据
    this.fetchDevicePositions();

    // 启动监测记录轮播
    this.startMonitorLogCarousel();
  },

  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      this.initDeviceStatusChart();

      // 在DOM完全渲染后检查并初始化加速度图表
      if (this.hasDeviceData(this.currentDevice.id)) {
        this.initAccelerationChart();
      }
    });

    this.initLiquidChart();
    // 添加全屏变化监听
    const fullscreenHandler = () => {
      this.isFullscreen = document.fullscreenElement !== null;
      this.$nextTick(() => {
        if (this.liquidChart) {
          this.liquidChart.resize();
          // 重新应用基础样式
          const container = document.querySelector('.score-circle');
          if (container) {
            this.liquidChart.resize({
              width: 160,
              height: 160
            });
          }
          this.updateLiquidChart(this.healthScore.score);
        }

        // 在全屏变化时自动刷新加速度图表
        if (this.accelerationChart) {
          this.accelerationChart.resize();

          // 延迟重绘以确保图表已经调整大小
          setTimeout(() => {
            const option = this.getAccelerationChartOption();
            this.accelerationChart.setOption(option);
          }, 300);
        }
      });
    };

    document.addEventListener('fullscreenchange', fullscreenHandler);
    document.addEventListener('webkitfullscreenchange', fullscreenHandler);
    document.addEventListener('onfullscreenchange', fullscreenHandler);
    document.addEventListener('MSFullscreenChange', fullscreenHandler);

    // 添加全屏变化监听
    document.addEventListener('fullscreenchange', this.handleFullscreenChange);

    // 增加加速度图表数据更新频率，使波动更明显
    if (this.accelerationTimer) {
      clearInterval(this.accelerationTimer);
    }
    this.accelerationTimer = setInterval(() => {
      this.updateAccelerationChart();
    }, 5000); // 5秒钟刷新一次
  },
  beforeDestroy() {
    this.stopDataUpdate()
    if (this.usageChart) {
      this.usageChart.dispose()
    }
    if (this.accelerationChart) {
      this.accelerationChart.dispose()
    }
    if (this.runningRateChart) {
      this.runningRateChart.dispose()
    }
    window.removeEventListener('resize', this.handleResize)

    // 移除监听器
    document.removeEventListener('fullscreenchange', this.fullscreenHandler);
    document.removeEventListener('webkitfullscreenchange', this.fullscreenHandler);
    document.removeEventListener('onfullscreenchange', this.fullscreenHandler);
    document.removeEventListener('MSFullscreenChange', this.fullscreenHandler);
    if (this.liquidChart) {
      this.liquidChart.dispose()
      this.liquidChart = null
    }
    if (this.accelerationTimer) {
      clearInterval(this.accelerationTimer);
      this.accelerationTimer = null;
    }
    if (this.deviceStatusChart) {
      this.deviceStatusChart.dispose();
      this.deviceStatusChart = null;
    }
    // 移除监听器
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
    if (this.monitorLogTimer) {
      clearInterval(this.monitorLogTimer);
      this.monitorLogTimer = null;
    }
    this.stopAutoDeviceHover(); // 组件销毁前停止自动悬浮
  },
  computed: {

  },
  methods: {
    // Helper function to format date/time for API calls
    formatTimeForApi(date) {
      if (!(date instanceof Date)) {
        date = new Date(date);
      }
      if (isNaN(date.getTime())) {
        console.error("Invalid date received in formatTimeForApi:", date);
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    async loadHistoricalAccelerationData(deviceId) {
      if (!deviceId) return;

      const endTime = new Date();
      const startTime = new Date(endTime.getTime() - 10 * 60 * 1000); // Last 10 minutes

      const formattedStartTime = this.formatTimeForApi(startTime);
      const formattedEndTime = this.formatTimeForApi(endTime);

      try {
        const res = await getWaveformDataByrangeTime(deviceId, formattedStartTime, formattedEndTime);
        if (res.code === 200 && res.data && res.data.length > 0) {
          const historicalData = res.data[0]; // Assuming the first element contains the relevant data
          const extraData = historicalData.extraData || {};
          const timestamps = historicalData.timestamps || [];

          const numPoints = 60; // Desired number of points for the chart

          // Initialize arrays for processed data
          let newTimeData = Array(numPoints).fill(null);
          let newRmsX = Array(numPoints).fill(null);
          let newRmsY = Array(numPoints).fill(null);
          let newRmsZ = Array(numPoints).fill(null);
          let newPeakX = Array(numPoints).fill(null);
          let newPeakY = Array(numPoints).fill(null);
          let newPeakZ = Array(numPoints).fill(null);

          const apiRmsX = extraData.xRmsData || [];
          const apiRmsY = extraData.yRmsData || [];
          const apiRmsZ = extraData.zRmsData || [];
          const apiPeakX = extraData.xPeakData || [];
          const apiPeakY = extraData.yPeakData || [];
          const apiPeakZ = extraData.zPeakData || [];

          const availablePoints = timestamps.length;
          const startIndex = Math.max(0, availablePoints - numPoints);
          const pointsToProcess = availablePoints - startIndex;

          for (let i = 0; i < pointsToProcess; i++) {
            const apiIndex = startIndex + i;
            const chartIndex = numPoints - pointsToProcess + i;

            if (timestamps[apiIndex]) {
              newTimeData[chartIndex] = new Date(timestamps[apiIndex]).toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
              });
            }
            newRmsX[chartIndex] = apiRmsX[apiIndex] !== undefined ? apiRmsX[apiIndex] : null;
            newRmsY[chartIndex] = apiRmsY[apiIndex] !== undefined ? apiRmsY[apiIndex] : null;
            newRmsZ[chartIndex] = apiRmsZ[apiIndex] !== undefined ? apiRmsZ[apiIndex] : null;
            newPeakX[chartIndex] = apiPeakX[apiIndex] !== undefined ? apiPeakX[apiIndex] : null;
            newPeakY[chartIndex] = apiPeakY[apiIndex] !== undefined ? apiPeakY[apiIndex] : null;
            newPeakZ[chartIndex] = apiPeakZ[apiIndex] !== undefined ? apiPeakZ[apiIndex] : null;
          }

          // Ensure the device data structure exists
          if (!this.deviceAccelerationData[deviceId]) {
            // Create 10秒间隔的时间点（60个点，覆盖10分钟）
            const initialTimePoints = Array(60).fill('').map((_, index) => {
              const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
              return time.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit' // 添加秒显示
              });
            });
            this.deviceAccelerationData[deviceId] = {
              latheName: this.currentDevice.latheName || '', // Get from currentDevice or an alternative source
              putPlace: this.currentDevice.putPlace || '',  // Get from currentDevice
              deviceLocation: '', // These might need to be set from another source or kept empty
              bindLocation: '',
              rms: { x: [], y: [], z: [] },
              peak: { x: [], y: [], z: [] },
              timeData: initialTimePoints,
              lastUpdateTime: 0
            };
          }

          // Update the device's acceleration data store
          this.deviceAccelerationData[deviceId].timeData = newTimeData;
          this.deviceAccelerationData[deviceId].rms = { x: newRmsX, y: newRmsY, z: newRmsZ };
          this.deviceAccelerationData[deviceId].peak = { x: newPeakX, y: newPeakY, z: newPeakZ };
          this.deviceAccelerationData[deviceId].lastUpdateTime = Date.now(); // Mark as updated

          // Refresh the chart for the current device if it's the one being updated
          if (this.currentDevice.id === deviceId) {
            this.$nextTick(() => {
              if (this.hasDeviceData(deviceId)) { // hasDeviceData might need adjustment
                this.initAccelerationChart();
              }
            });
          }
        } else {
          console.warn(`No historical acceleration data found for device ${deviceId} in the last 10 minutes.`);
          // If no historical data, initialize with nulls as before,
          // so the live updates can still populate it.
          if (!this.deviceAccelerationData[deviceId]) {
            const timePoints = Array(60).fill('').map((_, index) => {
              const time = new Date(Date.now() - (59 - index) * 10000);
              return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
            });
            this.deviceAccelerationData[deviceId] = {
              latheName: this.currentDevice.latheName || '',
              putPlace: this.currentDevice.putPlace || '',
              deviceLocation: '', bindLocation: '',
              rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
              peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
              timeData: timePoints,
              lastUpdateTime: Date.now()
            };
          } else { // Ensure existing data is reset to nulls if history fetch fails
            this.deviceAccelerationData[deviceId].timeData = this.deviceAccelerationData[deviceId].timeData.map(() => null);
            this.deviceAccelerationData[deviceId].rms = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
            this.deviceAccelerationData[deviceId].peak = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
          }
          if (this.currentDevice.id === deviceId) {
            this.$nextTick(() => this.initAccelerationChart());
          }
        }
      } catch (error) {
        console.error('Failed to load historical acceleration data:', error);
        // Initialize with nulls on error too
        if (!this.deviceAccelerationData[deviceId]) {
          const timePoints = Array(60).fill('').map((_, index) => {
            const time = new Date(Date.now() - (59 - index) * 10000);
            return time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
          });
          this.deviceAccelerationData[deviceId] = {
            latheName: this.currentDevice.latheName || '',
            putPlace: this.currentDevice.putPlace || '',
            deviceLocation: '', bindLocation: '',
            rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
            peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
            timeData: timePoints,
            lastUpdateTime: Date.now()
          };
        } else {
          this.deviceAccelerationData[deviceId].timeData = this.deviceAccelerationData[deviceId].timeData.map(() => null);
          this.deviceAccelerationData[deviceId].rms = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
          this.deviceAccelerationData[deviceId].peak = { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) };
        }
        if (this.currentDevice.id === deviceId) {
          this.$nextTick(() => this.initAccelerationChart());
        }
      }
    },
    // 定时更新相关方法
    startDataUpdate() {
      this.getList() // 立即获取一次数据
      this.dataUpdateTimer = setInterval(() => {
        this.getList()
      }, this.updateInterval)
    },

    stopDataUpdate() {
      if (this.dataUpdateTimer) {
        clearInterval(this.dataUpdateTimer)
        this.dataUpdateTimer = null
      }
    },

    // 修改数据更新方法
    async getList() {
      try {
        this.dataStatus.updating = true;
        const res = await getStatus();

        if (res.code === 200) {
          // 将接口数据保存到 deviceStatusData
          this.deviceStatusData = res.data;

          // 按latheName分组设备数据
          const latheNameGroups = {};

          // 遍历所有设备数据，按latheName分组
          this.deviceStatusData.forEach(device => {
            if (device.latheName) {
              if (!latheNameGroups[device.latheName]) {
                latheNameGroups[device.latheName] = {
                  devices: [],
                  status: '离线',
                  collectTime: device.collectTime
                };
              }

              latheNameGroups[device.latheName].devices.push(device);

              // 记录最新的时间
              if (new Date(device.collectTime) > new Date(latheNameGroups[device.latheName].collectTime)) {
                latheNameGroups[device.latheName].collectTime = device.collectTime;
              }

              // 按优先级更新状态: 故障 > 正常 > 待机 > 离线
              if (device.status === '故障') {
                latheNameGroups[device.latheName].status = '故障';
              } else if (device.status === '正常' && latheNameGroups[device.latheName].status !== '故障') {
                latheNameGroups[device.latheName].status = '正常';
              } else if (device.status === '待机' &&
                latheNameGroups[device.latheName].status !== '故障' &&
                latheNameGroups[device.latheName].status !== '正常') {
                latheNameGroups[device.latheName].status = '待机';
              }
            }
          });

          // 更新latheNameSummaries
          this.latheNameSummaries = {}; // 清空旧数据
          Object.keys(latheNameGroups).forEach(latheName => {
            this.latheNameSummaries[latheName] = {
              status: latheNameGroups[latheName].status,
              collectTime: latheNameGroups[latheName].collectTime,
              // 如果需要，还可以存储其他聚合信息，例如该latheName下的设备ID列表
              // deviceIds: latheNameGroups[latheName].devices.map(d => d.deviceId)
            };
          });

          // 统计各状态设备数量
          const stats = {
            normal: 0,  // 正常
            warning: 0, // 故障
            waiting: 0, // 待机
            offline: 0  // 离线
          };

          // 遍历每个latheName设备组，统计状态
          Object.values(latheNameGroups).forEach(latheData => {
            switch (latheData.status) {
              case '正常':
                stats.normal++;
                break;
              case '故障':
                stats.warning++;
                break;
              case '待机':
                stats.waiting++;
                break;
              default:
                stats.offline++;
                break;
            }
          });

          // 注释掉动态更新设备总数的代码，保持设备总数为固定值35
          // const totalLatheNames = Object.keys(latheNameGroups).length;
          // if (totalLatheNames > 0) {
          //     this.totalDevices = totalLatheNames;
          // }

          // 计算离线设备数量 - 总设备数保持固定为35
          stats.offline = this.totalDevices - (stats.normal + stats.warning + stats.waiting);

          // 更新设备状态统计
          this.deviceStatus = {
            normalCount: stats.normal,
            normalRate: Math.round((stats.normal / this.totalDevices) * 100),
            warningCount: stats.warning,
            warningRate: Math.round((stats.warning / this.totalDevices) * 100),
            waitingCount: stats.waiting,
            waitingRate: Math.round((stats.waiting / this.totalDevices) * 100),
            offlineCount: stats.offline,
            offlineRate: Math.round((stats.offline / this.totalDevices) * 100)
          };

          // 更新圆环进度条
          this.updateCircleProgress();

          // 不再在此处更新监测记录
          // this.updateMonitorLog(latheNameGroups);

          // 更新最后更新时间
          this.dataStatus.lastUpdate = new Date().toLocaleTimeString();

          // 更新健康评分
          this.healthScore = this.calculateHealthScore(latheNameGroups);

          // 更新完数据后更新图表
          this.$nextTick(() => {
            if (this.deviceStatusChart) {
              this.initDeviceStatusChart();
            }
          });
        }
      } catch (error) {
        console.error('获取设备状态失败:', error);
      } finally {
        this.dataStatus.updating = false;
      }
    },
// 计算使用率数据
// 计算仪表盘值
// 更新监控日志 - 基于latheName
    getDeviceStatus(deviceId) {
      const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
      if (!device) return '离线';
      return device.status || '离线';
    },
    initCharts() {
      this.$nextTick(() => {
        try {
          // 使用率曲线图表
          if (!this.usageChart && document.getElementById('usageChart')) {
            this.usageChart = echarts.init(document.getElementById('usageChart'))
            this.initUsageChart()
          }

          // 加速度图表初始化
          if(!this.accelerationChart && document.getElementById('accelerationChart')){
            this.accelerationChart = echarts.init(document.getElementById('accelerationChart'))
            // 使用统一的配置
            this.accelerationChart.setOption(this.getAccelerationChartOption())
          }
          // 立即获取并更新加速度数据
          this.updateAccelerationChart()

          // 启动定时更新
          if (!this.accelerationTimer) {
            this.accelerationTimer = setInterval(() => {
              this.updateAccelerationChart();
            }, 2000);
          }

          // 添加窗口大小变化监听
          window.addEventListener('resize', this.handleResize);

          // 运行率图表
          if (!this.runningRateChart && document.getElementById('runningRateChart')) {
            this.runningRateChart = echarts.init(document.getElementById('runningRateChart'))
            this.initRunningRateChart()
          }

          // 删除以下开工率图表初始化代码
          // if (!this.shiftRateChart && document.getElementById('shiftRateChart')) {
          //     this.shiftRateChart = echarts.init(document.getElementById('shiftRateChart'))
          //     this.initShiftRateChart()
          // }

          if (!this.comparisonChart && document.getElementById('comparisonChart')) {
            this.comparisonChart = echarts.init(document.getElementById('comparisonChart'))
            this.initSensorStatusChart()
          }
        } catch (error) {
          console.error('初始化图表失败:', error);
        }
      });
    },
    handleResize() {
      if (this.usageChart) {
        this.usageChart.resize()
      }
      if (this.accelerationChart) {
        this.accelerationChart.resize()
      }
      if (this.runningRateChart) {
        this.runningRateChart.resize()
      }
      if (this.comparisonChart) {
        this.comparisonChart.resize()
      }
      if (this.deviceStatusChart) {
        this.deviceStatusChart.resize();
      }
    },
    // 修改 updateAccelerationChart 方法
    async updateAccelerationChart() {
      try {
        const res = await getAccelerationData();

        if (res.code === 200) {
          // 获取当前选中的位置，以便在更新后恢复
          const currentSelectedPosition = this.currentPosition;

          // 初始化映射关系
          this.latheNameToDeviceMap = {};

          // 首先处理latheName的映射关系
          res.data.forEach(deviceData => {
            if (deviceData.latheName) {
              // 确保每个latheName对应的设备ID数组存在
              if (!this.latheNameToDeviceMap[deviceData.latheName]) {
                this.latheNameToDeviceMap[deviceData.latheName] = [];
              }

              // 添加设备ID到对应的latheName下
              if (!this.latheNameToDeviceMap[deviceData.latheName].includes(deviceData.deviceId)) {
                this.latheNameToDeviceMap[deviceData.latheName].push(deviceData.deviceId);
              }
            }
          });

          // 确保所有DevicesId中的设备都被映射到某个latheName
          this.DevicesId.forEach(deviceId => {
            // 检查此设备是否已经在latheNameToDeviceMap中
            let found = false;
            for (const latheName in this.latheNameToDeviceMap) {
              if (this.latheNameToDeviceMap[latheName].includes(deviceId)) {
                found = true;
                break;
              }
            }

            // 如果未在任何latheName中找到，添加到默认latheName
            if (!found) {
              const defaultName = this.getDeviceName(deviceId);
              if (!this.latheNameToDeviceMap[defaultName]) {
                this.latheNameToDeviceMap[defaultName] = [];
              }
              this.latheNameToDeviceMap[defaultName].push(deviceId);
            }
          });

          // 提取唯一的latheName列表
          this.uniqueLatheNames = Object.keys(this.latheNameToDeviceMap);

          // 遍历所有获取到的设备数据
          res.data.forEach(deviceData => {
            const deviceId = deviceData.deviceId;

            // 如果这个设备还没有数据结构，初始化一个
            if (!this.deviceAccelerationData[deviceId]) {
              // 创建10秒间隔的时间点（60个点，覆盖10分钟）
              const timePoints = Array(60).fill('').map((_, index) => {
                const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
                return time.toLocaleTimeString('zh-CN', {
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit' // 添加秒显示
                });
              });

              // 初始化设备数据结构
              this.deviceAccelerationData[deviceId] = {
                latheName: deviceData.latheName || null,
                putPlace: deviceData.putPlace || '',
                deviceLocation: deviceData.deviceLocation || '',
                bindLocation: deviceData.bindLocation || '',
                rms: {
                  x: Array(60).fill(null),
                  y: Array(60).fill(null),
                  z: Array(60).fill(null)
                },
                peak: {
                  x: Array(60).fill(null),
                  y: Array(60).fill(null),
                  z: Array(60).fill(null)
                },
                timeData: timePoints, // 使用统一的时间点生成
                lastUpdateTime: Date.now() // 记录最后更新时间
              };
            }

            // 更新设备的加速度数据
            const deviceAccData = this.deviceAccelerationData[deviceId];

            // 更新设备名称，但不覆盖安装位置（如果当前设备已选择特定位置）
            if (deviceData.latheName) {
              deviceAccData.latheName = deviceData.latheName;
            }

            // 只有当不是当前选中的设备时，才更新putPlace
            if (deviceId !== this.currentDevice.id) {
              if (deviceData.putPlace) {
                deviceAccData.putPlace = deviceData.putPlace;
              }
            }

            if (deviceData.deviceLocation) {
              deviceAccData.deviceLocation = deviceData.deviceLocation;
            }
            if (deviceData.bindLocation) {
              deviceAccData.bindLocation = deviceData.bindLocation;
            }

            // 检查是否需要更新数据点
            const now = Date.now();
            const timeSinceLastUpdate = now - (deviceAccData.lastUpdateTime || 0);

            // 如果距离上次更新超过5秒或者是首次更新，则添加新的数据点并实现左移效果
            if (timeSinceLastUpdate >= 5000 || !deviceAccData.lastUpdateTime) {
              // 更新时间数据 - 整体左移
              for (let i = 0; i < 59; i++) {
                deviceAccData.timeData[i] = deviceAccData.timeData[i + 1];
              }
              // 添加最新时间点
              const currentTime = new Date();
              deviceAccData.timeData[59] = currentTime.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit' // 添加秒显示
              });

              // RMS数据左移并更新最新点
              for (let i = 0; i < 59; i++) {
                deviceAccData.rms.x[i] = deviceAccData.rms.x[i + 1];
                deviceAccData.rms.y[i] = deviceAccData.rms.y[i + 1];
                deviceAccData.rms.z[i] = deviceAccData.rms.z[i + 1];
              }

              // 添加最新RMS数据，使用真实数据
              deviceAccData.rms.x[59] = deviceData.xrms || 0;
              deviceAccData.rms.y[59] = deviceData.yrms || 0;
              deviceAccData.rms.z[59] = deviceData.zrms || 0;

              // Peak数据左移并更新最新点
              for (let i = 0; i < 59; i++) {
                deviceAccData.peak.x[i] = deviceAccData.peak.x[i + 1];
                deviceAccData.peak.y[i] = deviceAccData.peak.y[i + 1];
                deviceAccData.peak.z[i] = deviceAccData.peak.z[i + 1];
              }

              // 添加最新Peak数据，使用真实数据
              deviceAccData.peak.x[59] = deviceData.xpeak || 0;
              deviceAccData.peak.y[59] = deviceData.ypeak || 0;
              deviceAccData.peak.z[59] = deviceData.zpeak || 0;

              // 更新最后更新时间
              deviceAccData.lastUpdateTime = now;
            } else {
              // 如果不需要添加新的数据点，只更新最新点的值
              const lastIndex = 59;

              // 更新最新点的RMS数据
              deviceAccData.rms.x[lastIndex] = deviceData.xrms || 0;
              deviceAccData.rms.y[lastIndex] = deviceData.yrms || 0;
              deviceAccData.rms.z[lastIndex] = deviceData.zrms || 0;

              // 更新最新点的Peak数据
              deviceAccData.peak.x[lastIndex] = deviceData.xpeak || 0;
              deviceAccData.peak.y[lastIndex] = deviceData.ypeak || 0;
              deviceAccData.peak.z[lastIndex] = deviceData.zpeak || 0;
            }

            // 如果是当前选中的设备，更新设备名称，但保持当前选中的安装位置不变
            if (deviceId === this.currentDevice.id) {
              if (deviceData.latheName) {
                this.currentDevice.latheName = deviceData.latheName;
                this.currentDevice.name = deviceData.latheName;
              }

              // 如果当前没有选择特定位置，但有新的位置信息，则更新
              if (!this.currentPosition && deviceData.putPlace) {
                this.currentDevice.putPlace = deviceData.putPlace;
                this.currentPosition = deviceData.putPlace;
              } else {
                // 否则保持当前选择的位置不变
                this.currentDevice.putPlace = this.currentPosition;
              }

              // 保持当前选中的位置不变，但更新可用位置列表
              this.updateDevicePositions(deviceData.latheName, false);
            }
          });

          // 如果有保存的位置选择，恢复它
          if (currentSelectedPosition) {
            this.currentPosition = currentSelectedPosition;
          }

          // 安全更新当前选中设备的图表
          this.$nextTick(() => {
            // 先检查DOM结构和数据有效性
            const chartContainer = document.getElementById('accelerationChart');
            if (chartContainer && this.hasDeviceData(this.currentDevice.id)) {
              // 确保图表实例存在
              if (!this.accelerationChart || this.accelerationChart.isDisposed()) {
                this.accelerationChart = echarts.init(chartContainer);
              }

              // 更新图表
              const option = this.getAccelerationChartOption();
              this.accelerationChart.setOption(option);
            }
          });
        }
      } catch (error) {
        console.error('更新加速度数据失败:', error);
      }
    },
    selectDevice(deviceId) {
      // 获取当前设备的latheName
      const deviceData = this.deviceAccelerationData[deviceId];
      const latheName = deviceData?.latheName || this.getDeviceName(deviceId);

      // 使用latheName更新当前设备
      this.currentDevice = {
        id: deviceId,
        name: latheName,
        latheName: latheName,
        putPlace: deviceData?.putPlace || '',
      };
      // this.loadHistoricalAccelerationData(deviceId); // Load historical data

      // 清除旧的图表实例
      if (this.accelerationChart && !this.accelerationChart.isDisposed()) {
        this.accelerationChart.dispose();
        this.accelerationChart = null;
      }

      // 重置位置数据
      this.devicePositions = [];
      this.currentPosition = '';

      // Load historical data and then initialize chart
      this.loadHistoricalAccelerationData(deviceId).then(() => {
        // 如果设备有数据且有latheName，获取该latheName下的所有putPlace
        if (latheName && this.hasDeviceData(deviceId)) {
          this.updateDevicePositions(latheName);
        } else {
          // 否则直接获取该设备的位置数据
          getAccelerationData().then(res => {
            if (res.code === 200) {
              const deviceDataList = res.data.filter(item => item.deviceId === deviceId);

              if (deviceDataList.length > 0) {
                // 更新latheName，然后通过latheName获取putPlace列表
                const fetchedLatheName = deviceDataList[0].latheName;
                if (fetchedLatheName) {
                  this.currentDevice.latheName = fetchedLatheName;
                  this.currentDevice.name = fetchedLatheName;
                  this.updateDevicePositions(fetchedLatheName);
                } else {
                  // 如果没有latheName，则直接提取putPlace
                  const positions = new Set();
                  deviceDataList.forEach(item => {
                    if (item.putPlace && typeof item.putPlace === 'string') {
                      positions.add(item.putPlace);
                    }
                  });

                  this.devicePositions = Array.from(positions);

                  if (this.devicePositions.length > 0) {
                    this.currentPosition = this.devicePositions[0];
                  }
                }

                // 更新当前设备putPlace
                this.currentDevice.putPlace = deviceDataList[0].putPlace || '';
              }
            }

            // 在DOM更新后初始化图表
            this.$nextTick(() => {
              if (this.hasDeviceData(deviceId)) {
                this.initAccelerationChart();
              }
            });
          }).catch(error => {
            console.error('获取设备数据失败:', error);
            this.$nextTick(() => {
              if (this.hasDeviceData(deviceId)) {
                this.initAccelerationChart();
              }
            });
          });
        }
        this.healthScore = this.calculateHealthScore(); // this was outside, moved in or should be outside?
        // It seems to depend on deviceStatusData not acceleration data directly.
        // Let's assume it can stay where it was or be called after this .then()
      });
      this.healthScore = this.calculateHealthScore(); // Placed here assuming it should run regardless of async history load for chart
    },

// 修改初始化加速度图表的方法
    initAccelerationChart() {
      // 确保DOM元素存在，且设备有数据
      const chartContainer = document.getElementById('accelerationChart');
      if (!chartContainer || !this.hasDeviceData(this.currentDevice.id)) {
        return;
      }

      // 如果图表实例不存在或已被销毁，则重新创建
      if (!this.accelerationChart || this.accelerationChart.isDisposed()) {
        this.accelerationChart = echarts.init(chartContainer);
      }

      // 设置图表选项
      const option = this.getAccelerationChartOption();
      this.accelerationChart.setOption(option, true);

      // 确保图表响应窗口大小变化
      if (this.accelerationChart) {
        this.accelerationChart.resize();
      }
    },

    // 计算健康评分 - 基于latheName
    calculateHealthScore(latheNameGroups = null) {
      // 初始分数为100
      let score = 100;
      const details = [];
      let faultCount = 0;

      // 如果没有传入latheName分组，则重新构建
      if (!latheNameGroups) {
        latheNameGroups = {};

        // 按latheName分组统计
        this.deviceStatusData.forEach(device => {
          if (device.latheName) {
            if (!latheNameGroups[device.latheName]) {
              latheNameGroups[device.latheName] = {
                devices: [device],
                status: device.status || '离线'
              };
            } else {
              latheNameGroups[device.latheName].devices.push(device);

              // 按优先级更新状态
              if (device.status === '故障') {
                latheNameGroups[device.latheName].status = '故障';
              } else if (device.status === '正常' && latheNameGroups[device.latheName].status !== '故障') {
                latheNameGroups[device.latheName].status = '正常';
              } else if (device.status === '待机' &&
                latheNameGroups[device.latheName].status !== '故障' &&
                latheNameGroups[device.latheName].status !== '正常') {
                latheNameGroups[device.latheName].status = '待机';
              }
            }
          }
        });
      }

      // 遍历每个latheName设备组，检查是否有故障
      Object.entries(latheNameGroups).forEach(([latheName, latheData]) => {
        if (latheData.status === '故障') {
          faultCount++;
          score = Math.max(0, score - 50); // 每台故障设备扣50分，不低于0分
          details.push(`设备 ${latheName} 故障 -50分`);
        }
      });

      // 确定健康状态
      let status;
      if (score >= 80) {
        status = 'normal';
      } else if (score >= 50) {
        status = 'warning';
      } else {
        status = 'error';
      }

      // 如果没有故障设备，添加正常运行信息
      if (faultCount === 0) {
        details.push('所有设备运行正常');
      }

      // 更新液体图表
      this.$nextTick(() => {
        this.updateLiquidChart(score);
      });

      return {
        score,
        details,
        status
      };
    },
    handleImageError(e) {
      console.error('图片加载失败');
      e.target.src = require('../../../assets/detect/offline.png'); // 加载失败时使用离线图标
    },
    toggleFullscreen() {
      if (!document.fullscreenElement) {
        const dashboard = document.querySelector('.dashboard');
        if (dashboard.requestFullscreen) {
          dashboard.requestFullscreen();
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        }
      }
    },
    handleFullscreenChange() {
      this.$nextTick(() => {
        if (this.liquidChart) {
          const container = document.querySelector('.score-circle');
          if (container) {
            // 根据全屏状态设置不同尺寸
            const size = document.fullscreenElement ? 150 : 120;
            this.liquidChart.resize({
              width: size,
              height: size
            });
            // 重新定位图表
            if (document.fullscreenElement) {
              container.style.left = '-40px';
            } else {
              container.style.left = '0';
            }
          }
          this.updateLiquidChart(this.healthScore.score);
        }
      });
    },
    initUsageChart() {
      const option = {
        grid: {
          top: 10,
          left: 30,  // 增加左边距以显示完整的Y轴标签
          right: 20,
          bottom: 30
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,  // 让线条从起点开始
          data: ['3.30', '3.31', '4.1', '4.2', '4.3', '4.4', '4.5'],  // 修改为与图片一致的日期格式
          axisLine: { lineStyle: { color: 'rgba(255,255,255,0.2)' } },
          axisLabel: { color: '#8f9bb3' }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          interval: 25,  // 设置刻度间隔为25
          axisLine: { lineStyle: { color: 'rgba(255,255,255,0.2)' } },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255,255,255,0.3)',
              type: 'dashed'  // 使用虚线网格
            }
          },
          axisLabel: {
            color: '#8f9bb3',
            formatter: '{value}'  // 移除百分号，与图片保持一致
          }
        },
        series: [{
          data: [90, 80, 10, 60, 45, 25, 50],  // 根据图片更新数据点
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          lineStyle: {
            color: '#00a0e9',  // 使用蓝色线条
            width: 2
          },
          itemStyle: {
            color: '#00a0e9',
            borderWidth: 2,
            borderColor: '#fff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(0,160,233,0.3)' },
              { offset: 1, color: 'rgba(0,160,233,0.1)' }
            ])
          }
        }]
      };

      this.usageChart.setOption(option);
    },
    initRunningRateChart() {
      const option = {
        grid: {
          top: 10,
          left: 40,
          right: 20,
          bottom: 30
        },
        xAxis: {
          type: 'category',
          data: ['3.28', '', '3.30', '', '4.1', '', '4.3', '', '4.5'],  // 修改为图片中的日期
          axisLine: { lineStyle: { color: 'rgba(255,255,255,0.2)' } },
          axisLabel: {
            color: '#8f9bb3',
            interval: 0  // 显示所有标签
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          interval: 25,  // 设置刻度间隔为25
          axisLine: { lineStyle: { color: 'rgba(255,255,255,0.2)' } },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255,255,255,0.3)',
              type: 'dashed'  // 使用虚线网格
            }
          },
          axisLabel: {
            color: '#8f9bb3',
            formatter: '{value}%'  // 添加百分号
          }
        },
        series: [
          {
            type: 'bar',
            data: [78, 28, 48, 47, 23, 69, 27, 60, 12, 30],  // 每个时间点的第二个柱子数据
            itemStyle: {
              color: '#00a0e9'  // 使用蓝色
            }
          }
        ]
      };

      this.runningRateChart.setOption(option);
    },
    initLiquidChart() {
      if (!this.liquidChart) {
        this.liquidChart = echarts.init(document.querySelector('.score-circle'))
      }

      const score = this.healthScore.score / 100
      const option = {
        series: [{
          type: 'liquidFill',
          data: [score, score * 0.9], // 两层水波
          radius: '95%',
          color: [{
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(255, 77, 79, 0.8)'
            }, {
              offset: 1,
              color: 'rgba(255, 77, 79, 0.3)'
            }]
          }, {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(255, 77, 79, 0.6)'
            }, {
              offset: 1,
              color: 'rgba(255, 77, 79, 0.2)'
            }]
          }],
          backgroundStyle: {
            color: 'transparent'
          },
          outline: {
            show: true,
            borderDistance: 2,
            itemStyle: {
              color: 'none',
              borderColor: '#ff4d4f',
              borderWidth: 2,
              shadowBlur: 0
            }
          },
          label: {
            show: true,
            position: ['50%', '45%'],
            formatter: function () {
              return [
                '{title|我的评分}',
                '{value|' + this.healthScore.score + '}'
              ].join('\n')
            }.bind(this),
            rich: {
              title: {
                fontSize: 14,
                color: '#fff',
                padding: [0, 0, 10, 0],
                fontWeight: 'normal',
                align: 'center'
              },
              value: {
                fontSize: 36,
                color: '#fff',
                fontWeight: 'normal',
                align: 'center'
              }
            }
          },
          amplitude: 12, // 水波振幅
          waveLength: '80%', // 水波长度
          phase: 0,
          period: 4000, // 水波周期
          direction: 'right',
          shape: 'circle',
          waveAnimation: true,
          animationEasing: 'linear',
          animationEasingUpdate: 'linear',
          animationDuration: 2000,
          animationDurationUpdate: 1000
        }]
      }

      this.liquidChart.setOption(option)
    },

    // 更新水位图数据
    updateLiquidChart(score = 100) {
      if (!this.liquidChart) {
        this.liquidChart = echarts.init(document.querySelector('.score-circle'));
      }

      const isFullscreen = document.fullscreenElement !== null;

      // 根据分数设置不同的颜色
      let color;
      if (score >= 80) {
        color = {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(32, 184, 78, 0.8)' // 绿色
          }, {
            offset: 1,
            color: 'rgba(32, 184, 78, 0.3)'
          }]
        };
      } else if (score >= 50) {
        color = {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(255, 179, 0, 0.8)' // 黄色
          }, {
            offset: 1,
            color: 'rgba(255, 179, 0, 0.3)'
          }]
        };
      } else {
        color = {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(255, 77, 79, 0.8)' // 红色
          }, {
            offset: 1,
            color: 'rgba(255, 77, 79, 0.3)'
          }]
        };
      }

      const option = {
        series: [{
          type: 'liquidFill',
          data: [score/100, (score/100)*0.9],
          radius: '95%',
          color: [color, color],
          backgroundStyle: {
            color: 'transparent'
          },
          outline: {
            show: true,
            borderDistance: 2,
            itemStyle: {
              color: 'none',
              borderColor: score >= 80 ? '#20b84e' : (score >= 50 ? '#ffb300' : '#ff4d4f'),
              borderWidth: 2,
              shadowBlur: 0
            }
          },
          label: {
            show: true,
            position: ['50%', '45%'],
            formatter: function() {
              return [
                '{title|设备健康评分}',
                '{value|' + score + '}'
              ].join('\n')
            },
            rich: {
              title: {
                fontSize: isFullscreen ? 16 : 14,
                color: '#fff',
                padding: [0, 0, 10, 0]
              },
              value: {
                fontSize: isFullscreen ? 42 : 36,
                color: '#fff'
              }
            }
          }
        }]
      };

      this.liquidChart.setOption(option);
    },
    switchAccelerationType(type) {
      this.accelerationType = type;

      // 在类型切换后重新渲染图表
      this.$nextTick(() => {
        if (this.hasDeviceData(this.currentDevice.id)) {
          this.initAccelerationChart();
        }
      });
    },
    // 添加初始化传感器运行状态图表的方法
    initSensorStatusChart() {
      if (!this.comparisonChart) return;

      const option = {
        series: [{
          type: 'gauge',
          startAngle: 180,
          endAngle: 0,
          min: 0,
          max: 100,
          splitNumber: 10,
          radius: '65%',
          center: ['30%', '45%'],
          progress: {
            show: true,
            roundCap: true,
            width: 15,
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 1,
                y2: 0,
                colorStops: [{
                  offset: 0,
                  color: '#00ff4c'
                }, {
                  offset: 1,
                  color: '#39ffa1'
                }]
              },
              shadowColor: 'rgba(0, 255, 76, 0.5)',
              shadowBlur: 10
            }
          },
          pointer: {
            show: true,
            length: '60%',
            width: 3,
            itemStyle: {
              color: '#00ff4c',
              shadowColor: 'rgba(0, 255, 76, 0.5)',
              shadowBlur: 5
            }
          },
          axisLine: {
            roundCap: true,
            lineStyle: {
              width: 15,
              color: [
                [1, {
                  type: 'linear',
                  colorStops: [{
                    offset: 0,
                    color: 'rgba(0, 255, 76, 0.05)'
                  }, {
                    offset: 1,
                    color: 'rgba(0, 255, 76, 0.1)'
                  }]
                }]
              ]
            }
          },
          axisTick: {
            show: true,
            distance: -15,
            length: 4,
            lineStyle: {
              color: '#ffffff',
              width: 1,
              opacity: 0.5
            }
          },
          splitLine: {
            show: true,
            distance: -15,
            length: 8,
            lineStyle: {
              color: '#ffffff',
              width: 2,
              opacity: 0.7
            }
          },
          axisLabel: {
            show: false
          },
          detail: {
            show: true,
            position: 'right',
            offsetCenter: this.isFullscreen ? [200, -30] : [180, -30],  // 全屏时调整位置
            formatter: function (value) {
              return [
                '{title|全力护航}',
                '{value|' + value + '%}',
                '{device|传感器：35台}'
              ].join('\n');
            },
            rich: {
              title: {
                fontSize: this.isFullscreen ? 22 : 16,  // 全屏时放大字号
                color: '#fff',
                padding: [0, 0, 15, 0],
                fontWeight: 'normal',
                align: 'left'
              },
              value: {
                fontSize: this.isFullscreen ? 42 : 32,  // 全屏时放大字号
                fontWeight: 'bold',
                color: '#fff',
                padding: [0, 0, 15, 0],
                align: 'left'
              },
              device: {
                fontSize: this.isFullscreen ? 20 : 14,  // 全屏时放大字号
                color: '#fff',
                padding: [0, 0, 0, 0],
                align: 'left'
              }
            }
          },
          data: [{
            value:100,
            name: ''
          }]
        }]
      };

      this.comparisonChart.setOption(option);
    },
    // 添加更新圆环进度条的方法
    updateCircleProgress() {
      const progressElement = document.querySelector('.circle-progress');
      if (progressElement) {
        // 设置CSS变量来控制圆环显示
        progressElement.style.setProperty('--normal-rate', this.deviceStatus.normalRate);
        progressElement.style.setProperty('--warning-rate', this.deviceStatus.warningRate);
        progressElement.style.setProperty('--waiting-rate', this.deviceStatus.waitingRate);
        // 离线率会自动填充剩余部分
      }
    },
    getStatusClass(status) {
      switch (status) {
        case '正常':
          return 'normal';
        case '待机':
          return 'waiting';
        case '故障':
          return 'warning';
        default:
          return 'offline';
      }
    },
// 修改加速度图表配置
    getAccelerationChartOption() {
      const deviceId = this.currentDevice.id;
      let deviceData = this.deviceAccelerationData[deviceId]; // Use let to allow reassignment

      // 如果没有数据，确保创建一个空的结构供图表使用，以保证formatter能运行
      if (!deviceData) {
        console.warn(`[getAccelerationChartOption] No deviceData for ${deviceId}, creating placeholder.`);
        const placeholderTimeData = Array(60).fill(null);
        // Create a minimal placeholder structure if it's truly missing
        // This helps the formatter logic to still execute with [0] and [59]
        this.deviceAccelerationData[deviceId] = {
          latheName: this.currentDevice.latheName || '未知设备',
          putPlace: this.currentDevice.putPlace || '',
          deviceLocation: '',
          bindLocation: '',
          rms: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
          peak: { x: Array(60).fill(null), y: Array(60).fill(null), z: Array(60).fill(null) },
          timeData: placeholderTimeData,
          lastUpdateTime: Date.now()
        };
        deviceData = this.deviceAccelerationData[deviceId]; // Assign the newly created placeholder
      }

      // 如果没有数据，返回空图表配置
      if (!deviceData) {
        return {
          xAxis: {
            type: 'category',
            data: []
          },
          yAxis: {
            type: 'value',
            name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
            splitLine: {
              lineStyle: {
                color: 'rgba(255,255,255,0.3)',
                type: 'dashed'
              }
            }
          },
          series: [
            {
              name: 'X轴',
              type: 'line',
              data: [],
              lineStyle: { color: 'red', width: 2 }
            },
            {
              name: 'Y轴',
              type: 'line',
              data: [],
              lineStyle: { color: 'yellow', width: 2 }
            },
            {
              name: 'Z轴',
              type: 'line',
              data: [],
              lineStyle: { color: 'green', width: 2 }
            }
          ],
          grid: {
            top: 40, // Reduced from 50
            left: 50,
            right: 30,
            bottom: 70, // Increased from 60 to 70
            // height: '85%' // Removed to allow auto-calculation based on top/bottom
          },
          legend: {
            show: true,
            top: 10,
            right: 10,
            textStyle: {
              color: 'rgba(255,255,255,0.8)',
              fontSize: 12
            },
            data: ['X轴', 'Y轴', 'Z轴']
          }
        };
      }

      const currentData = this.accelerationType === 'rms' ?
        deviceData.rms : deviceData.peak;

      // 计算数据的最大值和最小值，用于自适应Y轴
      let dataMax = 0;
      let dataMin = Number.MAX_VALUE;

      // 遍历所有数据点找出最大值和最小值
      ['x', 'y', 'z'].forEach(axis => {
        // 筛选掉0值，这些通常是初始化或无效数据
        const validData = currentData[axis].filter(val => val > 0);
        if (validData.length > 0) {
          const maxVal = Math.max(...validData);
          const minVal = Math.min(...validData);

          if (maxVal > dataMax) {
            dataMax = maxVal;
          }

          if (minVal < dataMin) {
            dataMin = minVal;
          }
        }
      });

      // 如果最小值仍然是初始值，或者数据都是0，则设置为0
      if (dataMin === Number.MAX_VALUE || dataMax === 0) {
        dataMin = 0;
        dataMax = 1; // 避免空图表
      }

      // 计算数据平均值和波动范围
      const avgValues = {};
      const fluctuationRanges = {};

      ['x', 'y', 'z'].forEach(axis => {
        // 筛选有效数据
        const validData = currentData[axis].filter(val => val !== null && val > 0); // Ensure nulls are filtered for calculation
        if (validData.length > 0) {
          // 计算平均值
          const sum = validData.reduce((acc, val) => acc + val, 0);
          avgValues[axis] = sum / validData.length;

          // 计算波动范围
          fluctuationRanges[axis] = Math.max(...validData) - Math.min(...validData);
        } else {
          avgValues[axis] = 0;
          fluctuationRanges[axis] = 0;
        }
      });

      // 智能调整Y轴范围
      const yAxisMin = 0;
      // Adjusted yAxisMax: slightly above data max, or a default small range if data is flat or zero.
      let yAxisMax = dataMax > 0 ? dataMax * 1.2 : 10;
      if (yAxisMax === 0 && dataMin === 0) yAxisMax = 10; // Handles all zero case specifically for a small default range
      if (yAxisMax <= yAxisMin) yAxisMax = yAxisMin + 10; // Ensure max is always greater than min

      // 设置适合的背景色和线条颜色，与参考图片类似
      const colors = {
        x: {
          line: '#4a7eff', // 蓝色
          area: 'rgba(74, 126, 255, 0.15)' // 淡蓝色透明
        },
        y: {
          line: '#59d666', // 绿色
          area: 'rgba(89, 214, 102, 0.15)' // 淡绿色透明
        },
        z: {
          line: '#ff5a5a', // 红色
          area: 'rgba(255, 90, 90, 0.15)' // 淡红色透明
        }
      };

      return {
        backgroundColor: 'rgba(250, 250, 250, 0.05)', // 略微亮一点的背景色
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>';

            params.forEach(param => {
              const color = param.color;
              const seriesName = param.seriesName;
              const value = param.value;

              result += `<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`;
              result += `${seriesName}: ${value.toFixed(3)} m/s²<br/>`;
            });

            return result;
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: 'rgba(255,255,255,0.5)',
              width: 1
            }
          },
          backgroundColor: 'rgba(50,50,50,0.9)',
          borderColor: 'rgba(255,255,255,0.3)',
          textStyle: {
            color: '#fff'
          }
        },
        xAxis: {
          type: 'category',
          data: deviceData.timeData,
          axisLabel: {
            color: 'rgba(255,255,255,0.7)',
            fontSize: 10,
            rotate: 0
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.3)'
            }
          },
          axisTick: {
            show: false // Keep ticks hidden for cleaner look if labels are also sparse/hidden
          },
          name: '',
          nameLocation: 'end',
          nameGap: 15, // Default is 15, can be reduced e.g. to 5 or 10 if needed
          nameTextStyle: {
            color: 'rgba(255,255,255,0.7)',
            fontSize: 10,
            padding: [0, 0, 0, 0] // Reset padding, or adjust e.g., [5,0,0,0] to push down slightly from axis line
          }
        },
        yAxis: {
          type: 'value',
          name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
          min: yAxisMin,
          max: yAxisMax,
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.3)',
              type: 'dashed'
            }
          },
          axisLabel: {
            formatter: function(value) {
              return value.toFixed(2);
            },
            color: 'rgba(255,255,255,0.7)'
          },
          nameTextStyle: {
            color: 'rgba(255,255,255,0.7)'
          }
        },
        series: [
          {
            name: 'X轴',
            type: 'line',
            showSymbol: false,
            smooth: true,
            lineStyle: {
              color: colors.x.line,
              width: 2
            },
            itemStyle: {
              color: colors.x.line,
              borderWidth: 2,
              borderColor: '#fff'
            },
            emphasis: {
              itemStyle: {
                color: '#fff',
                borderColor: colors.x.line,
                borderWidth: 3,
                shadowColor: 'rgba(74, 126, 255, 0.8)',
                shadowBlur: 5
              }
            },
            data: currentData.x,
            z: 1,
            areaStyle: {
              color: colors.x.area,
              origin: 'start'
            }
          },
          {
            name: 'Y轴',
            type: 'line',
            showSymbol: false,
            smooth: true,
            lineStyle: {
              color: colors.y.line,
              width: 2
            },
            itemStyle: {
              color: colors.y.line,
              borderWidth: 2,
              borderColor: '#fff'
            },
            emphasis: {
              itemStyle: {
                color: '#fff',
                borderColor: colors.y.line,
                borderWidth: 3,
                shadowColor: 'rgba(89, 214, 102, 0.8)',
                shadowBlur: 5
              }
            },
            data: currentData.y,
            z: 2,
            areaStyle: {
              color: colors.y.area,
              origin: 'start'
            }
          },
          {
            name: 'Z轴',
            type: 'line',
            showSymbol: false,
            smooth: true,
            lineStyle: {
              color: colors.z.line,
              width: 2
            },
            itemStyle: {
              color: colors.z.line,
              borderWidth: 2,
              borderColor: '#fff'
            },
            emphasis: {
              itemStyle: {
                color: '#fff',
                borderColor: colors.z.line,
                borderWidth: 3,
                shadowColor: 'rgba(255, 90, 90, 0.8)',
                shadowBlur: 5
              }
            },
            data: currentData.z,
            z: 3,
            areaStyle: {
              color: colors.z.area,
              origin: 'start'
            }
          }
        ],
        grid: {
          top: 40, // Reduced from 50
          left: 50,
          right: 30,
          bottom: 70, // Increased from 60 to 70
          // height: '85%' // Removed to allow auto-calculation based on top/bottom
        },
        legend: {
          show: true,
          top: 10,
          right: 10,
          textStyle: {
            color: 'rgba(255,255,255,0.8)',
            fontSize: 12
          },
          data: ['X轴', 'Y轴', 'Z轴']
        }
      };
    },
    // 初始化设备状态环形图
    initDeviceStatusChart() {
      if (!this.deviceStatusChart && document.querySelector('.circle-progress')) {
        this.deviceStatusChart = echarts.init(document.querySelector('.circle-progress'));
      }

      if (!this.deviceStatusChart) return;

      const option = {
        backgroundColor: 'transparent',
        title: {
          text: '可监测总数',
          subtext: this.totalDevices + '台设备',
          left: '23%',
          top: '29%',
          textAlign: 'center',
          textStyle: {
            fontSize: 14,
            color: '#8f9bb3',
            fontWeight: 'normal'
          },
          subtextStyle: {
            fontSize: 16,
            color: '#fff',
            fontWeight: 'bold',
            padding: [5, 0, 0, 0]
          }
        },
        series: [{
          type: 'pie',
          radius: ['70%', '90%'],    // 调整圆环大小比例
          center: ['26.5%', '45%'],    // 保持圆环位置
          startAngle: 90,
          label: {
            show: false
          },
          silent: true,
          animation: false,
          data: [
            {
              value: this.deviceStatus.normalRate || 0,
              name: '正常',
              itemStyle: {
                color: '#00ff4c'
              }
            },
            {
              value: this.deviceStatus.warningRate || 0,
              name: '故障',
              itemStyle: {
                color: '#ff2b2b'
              }
            },
            {
              value: this.deviceStatus.waitingRate || 0,
              name: '待机',
              itemStyle: {
                color: '#ffb300'
              }
            },
            {
              value: this.deviceStatus.offlineRate || 0,
              name: '离线',
              itemStyle: {
                color: '#808080'
              }
            }
          ]
        }],
        legend: {
          orient: 'vertical',
          left: '55%',
          top: '10%',
          itemGap: 15,
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: '#8f9bb3',
            fontSize: 14,
            rich: {
              name: {
                width: 32,
                padding: [0, 0, 0, 0]  // 减小右侧padding
              },
              value: {
                width: 32,  // 减小宽度
                align: 'right',
                padding: [0, 5, 0, 0],  // 减小右侧padding
                color: '#fff'
              },
              count: {
                width: 32,  // 减小宽度
                align: 'right',
                padding: [0, 0, 0, 0]
              }
            }
          },
          formatter: function (name) {
            const data = option.series[0].data;
            const item = data.find(item => item.name === name);
            const value = item ? item.value : 0;
            const count = item ? Math.round((value * this.totalDevices) / 100) : 0;
            return [
              '{name|' + name + '}',
              '{value|' + value + '%}',
              '{count|' + count + '台}'
            ].join('');
          }.bind(this)
        }
      };

      this.deviceStatusChart.setOption(option, true);

      // 添加窗口大小变化的监听
      window.addEventListener('resize', () => {
        this.deviceStatusChart.resize();
      });
    },
    switchWorkshop(workshopId) {
      this.currentWorkshop = workshopId;
      // 这里可以添加切换车间后的其他逻辑
    },
    // 添加预加载所有设备数据的方法
    async prefetchAccelerationData() {
      try {
        const res = await getAccelerationData();

        if (res.code === 200 && Array.isArray(res.data)) {
          // 初始化映射
          this.latheNameToDeviceMap = {};

          // 处理latheName的映射关系
          res.data.forEach(deviceData => {
            if (deviceData.latheName) {
              if (!this.latheNameToDeviceMap[deviceData.latheName]) {
                this.latheNameToDeviceMap[deviceData.latheName] = [];
              }
              if (!this.latheNameToDeviceMap[deviceData.latheName].includes(deviceData.deviceId)) {
                this.latheNameToDeviceMap[deviceData.latheName].push(deviceData.deviceId);
              }
            }
          });

          // 确保所有DevicesId中的设备都被映射到某个latheName
          this.DevicesId.forEach(deviceId => {
            // 检查此设备是否已经在latheNameToDeviceMap中
            let found = false;
            for (const latheName in this.latheNameToDeviceMap) {
              if (this.latheNameToDeviceMap[latheName].includes(deviceId)) {
                found = true;
                break;
              }
            }

            // 如果未在任何latheName中找到，添加到默认latheName
            if (!found) {
              const defaultName = this.getDeviceName(deviceId);
              if (!this.latheNameToDeviceMap[defaultName]) {
                this.latheNameToDeviceMap[defaultName] = [];
              }
              this.latheNameToDeviceMap[defaultName].push(deviceId);
            }
          });

          // 提取唯一的latheName列表
          this.uniqueLatheNames = Object.keys(this.latheNameToDeviceMap);

          // 提取位置数据
          const positions = new Set();
          res.data.forEach(item => {
            if (item.putPlace && typeof item.putPlace === 'string') {
              positions.add(item.putPlace);
            }
          });

          this.devicePositions = Array.from(positions);

          if (this.devicePositions.length > 0) {
            this.currentPosition = this.devicePositions[0];
          }
        }
      } catch (error) {
        console.error('预加载设备数据失败:', error);
      }
    },
    hasDeviceData(deviceId) {
      // 首先检查设备状态，如果是离线或待机，则直接返回false
      const deviceStatus = this.getDeviceStatus(deviceId);
      if (deviceStatus === '离线' || deviceStatus === '待机') {
        return false;
      }

      // 然后检查deviceAccelerationData是否存在并且数据是否有效
      const deviceData = this.deviceAccelerationData[deviceId];
      if (!deviceData) return false;

      // 检查是否所有数据都是0，如果都是0，可能没有真实数据
      const allZero = (
        deviceData.rms.x.every(val => val === 0) &&
        deviceData.rms.y.every(val => val === 0) &&
        deviceData.rms.z.every(val => val === 0) &&
        deviceData.peak.x.every(val => val === 0) &&
        deviceData.peak.y.every(val => val === 0) &&
        deviceData.peak.z.every(val => val === 0)
      );

      // 只有当状态正常且至少有一个轴有非零数据时，才认为有数据
      return !allZero;
    },
    switchPosition(position) {
      if (this.currentPosition !== position) {
        this.currentPosition = position;
        console.log('筛选后的数据:', position)
        // 更新当前位置的加速度数据
        this.updateAccelerationChartByPosition(); // This might update currentDevice.id
        // this.loadHistoricalAccelerationData(this.currentDevice.id); // Load historical data for the new position/device


      }
    },
    // 根据当前latheName和position筛选加速度数据
    updateAccelerationChartByPosition() {
      const latheName = this.currentDevice.latheName;
      if (!latheName || !this.currentPosition) return;

      getAccelerationData().then(res => {
        if (res.code === 200) {
          // 筛选当前latheName和当前位置的数据
          const filteredData = res.data.filter(item =>
            item.latheName === latheName &&
            item.putPlace === this.currentPosition
          );

          if (filteredData.length > 0) {
            const deviceData = filteredData[0];
            console.log('更新当前设备ID和位置:', deviceData)
            // 如果找到匹配的设备数据，使用该设备进行图表更新
            if (deviceData.deviceId && deviceData.deviceId !== this.currentDevice.id) {
              // 更新当前设备ID，但保持latheName和位置不变
              console.log('更新id:', deviceData.deviceId)

              this.currentDevice.id = deviceData.deviceId;
              this.currentDevice.putPlace = this.currentPosition;

              // 确保数据已加载
              if (!this.deviceAccelerationData[deviceData.deviceId]) {
                // 初始化设备数据
                // 与 updateAccelerationChart 中 timePoints 生成逻辑保持一致
                const timePoints = Array(60).fill('').map((_, index) => {
                  const time = new Date(Date.now() - (59 - index) * 10000); // 10秒 = 10000毫秒
                  return time.toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                  });
                });

                this.deviceAccelerationData[deviceData.deviceId] = {
                  latheName: latheName,
                  putPlace: this.currentPosition,
                  deviceLocation: deviceData.deviceLocation || '',
                  bindLocation: deviceData.bindLocation || '',
                  rms: {
                    x: Array(60).fill(null), // 统一为60点，null填充
                    y: Array(60).fill(null),
                    z: Array(60).fill(null)
                  },
                  peak: {
                    x: Array(60).fill(null), // 统一为60点，null填充
                    y: Array(60).fill(null),
                    z: Array(60).fill(null)
                  },
                  timeData: timePoints, // 使用统一的时间点生成
                  lastUpdateTime: Date.now()
                };
              }
            }
          }
        }
        // 重新初始化图表
        this.loadHistoricalAccelerationData(this.currentDevice.id).then(() => {
          this.$nextTick(() => {
            if (this.hasDeviceData(this.currentDevice.id)) {
              this.initAccelerationChart();
            }
          });
        });
      }).catch(error => {
        console.error('获取位置加速度数据失败:', error);
      });
    },
    // 获取设备安装位置数据
    async fetchDevicePositions() {
      try {
        const res = await getAccelerationData();

        if (res.code === 200 && Array.isArray(res.data)) {
          // 只获取当前设备的数据
          const currentDeviceData = res.data.filter(item =>
            item.deviceId === this.currentDevice.id
          );

          // 只有当设备状态正常且有数据时才提取位置信息
          if (currentDeviceData.length > 0 && this.hasDeviceData(this.currentDevice.id)) {
            // 从响应中提取putPlace数据
            const positions = new Set(); // 使用Set去重

            currentDeviceData.forEach(item => {
              if (item.putPlace && typeof item.putPlace === 'string') {
                positions.add(item.putPlace);
              }
            });

            // 转换为数组
            this.devicePositions = Array.from(positions);

            // 如果有位置数据，且当前没有选择的位置，则默认选中第一个
            if (this.devicePositions.length > 0 && !this.currentPosition) {
              this.currentPosition = this.devicePositions[0];
            }

            console.log('获取到设备安装位置：', this.devicePositions);
          } else {
            // 如果设备离线或待机，清空位置数据
            this.devicePositions = [];
            this.currentPosition = '';
          }
        }
      } catch (error) {
        console.error('获取设备安装位置失败:', error);
        this.devicePositions = [];
        this.currentPosition = '';
      }
    },
    getDeviceName(deviceId) {
      // 优先使用加速度数据中的latheName
      if (this.deviceAccelerationData[deviceId]?.latheName) {
        return this.deviceAccelerationData[deviceId].latheName;
      }

      // 其次在设备状态数据中查找
      const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
      if (device && device.latheName) {
        return device.latheName;
      }

      // 如果latheName为空，则使用Junker磨床+序号格式
      const idStr = String(deviceId);
      const suffix = idStr.length >= 4 ? idStr.slice(-4) : idStr;
      return `磨床${suffix}`;
    },
    // 添加一个方法用于根据latheName更新设备的putPlace列表
    updateDevicePositions(latheName, autoSelectFirst = true) {
      if (!latheName) return;

      // 获取设备位置数据
      getAccelerationData().then(res => {
        if (res.code === 200) {
          // 筛选具有相同latheName的所有设备数据
          const sameLatheDevices = res.data.filter(item => item.latheName === latheName);

          if (sameLatheDevices.length > 0) {
            // 提取位置信息
            const positions = new Set();
            sameLatheDevices.forEach(item => {
              if (item.putPlace && typeof item.putPlace === 'string') {
                positions.add(item.putPlace);
              }
            });

            this.devicePositions = Array.from(positions);

            // 如果有位置数据，且需要自动选择第一个位置，并且当前没有选择的位置
            if (this.devicePositions.length > 0 && autoSelectFirst && !this.currentPosition) {
              this.currentPosition = this.devicePositions[0];
            }

            console.log(`获取到 ${latheName} 的安装位置：`, this.devicePositions);
          }
        }
      }).catch(error => {
        console.error('获取设备位置数据失败:', error);
      });
    },
    getLatheNameStatus(latheName) {
      if (!latheName || !this.latheNameToDeviceMap[latheName]) {
        return '离线';
      }

      // 检查是否为没有真实latheName而自动生成的名称
      // 如果是通过getDeviceName方法生成的名称格式(磨床+数字)，且设备没有实际数据，则显示为离线
      if (latheName.match(/^磨床\d+$/) && !this.deviceHasRealLatheName(latheName)) {
        return '离线';
      }

      const deviceIds = this.latheNameToDeviceMap[latheName];
      let status = '离线';

      // 优先级：故障 > 正常 > 待机 > 离线
      for (const deviceId of deviceIds) {
        const deviceStatus = this.getDeviceStatus(deviceId);
        if (deviceStatus === '故障') {
          return '故障'; // 如果有任何设备故障，立即返回故障状态
        } else if (deviceStatus === '正常' && status !== '故障') {
          status = '正常'; // 如果有设备正常，且当前没有故障状态，设为正常
        } else if (deviceStatus === '待机' && status === '离线') {
          status = '待机'; // 如果有设备待机，且当前为离线状态，设为待机
        }
      }

      return status;
    },
    getLatheNameIcon(latheName) {
      const status = this.getLatheNameStatus(latheName);
      const iconMap = {
        '正常': require('../../../assets/detect/normal.png'),
        '故障': require('../../../assets/detect/warning.png'),
        '待机': require('../../../assets/detect/waiting.png'),
        '离线': require('../../../assets/detect/offline.png')
      };
      return iconMap[status] || require('../../../assets/detect/offline.png');
    },
    selectLatheNameDevice(latheName) {
      if (!latheName || !this.latheNameToDeviceMap[latheName]) {
        return;
      }

      // 从该latheName下获取一个有效的设备ID
      const deviceIds = this.latheNameToDeviceMap[latheName];
      let selectedDeviceId = deviceIds[0]; // 默认选择第一个

      // 优先选择状态为正常的设备
      for (const deviceId of deviceIds) {
        const deviceStatus = this.getDeviceStatus(deviceId);
        if (deviceStatus === '正常') {
          selectedDeviceId = deviceId;
          break;
        }
      }

      // 调用现有的selectDevice方法
      this.selectDevice(selectedDeviceId);
    },
// 检查设备是否有真实的latheName（非自动生成）
    deviceHasRealLatheName(latheName) {
      // 如果latheName不存在于latheNameToDeviceMap中，说明不是真实latheName
      if (!this.latheNameToDeviceMap[latheName]) {
        return false;
      }

      // 获取该latheName下的所有设备ID
      const deviceIds = this.latheNameToDeviceMap[latheName];

      // 检查是否有任何设备在加速度数据中有真实的latheName
      for (const deviceId of deviceIds) {
        // 如果在设备加速度数据中能找到相同的latheName，说明这是一个真实的latheName
        if (this.deviceAccelerationData[deviceId]?.latheName === latheName) {
          // 进一步确认这个latheName不是通过getDeviceName自动生成的
          const device = this.deviceStatusData.find(d => d.deviceId === deviceId);
          if (device && device.latheName === latheName) {
            return true;
          }
        }
      }

      // 如果没有找到匹配的真实latheName，返回false
      return false;
    },
    // 添加新的轮播更新监测记录的方法
    startMonitorLogCarousel() {
      if (this.monitorLogTimer) {
        clearInterval(this.monitorLogTimer);
      }

      this.updateMonitorLogCarousel(); // 立即执行一次

      this.monitorLogTimer = setInterval(() => {
        this.updateMonitorLogCarousel();
      }, 1000); // 修改为每1秒轮播一次
    },
    updateMonitorLogCarousel() {
      if (this.uniqueLatheNames.length === 0) {
        this.monitorLogs = [];
        this.newlyFaultyLatheNames.clear();
        return;
      }

      const localNewlyFaultyLatheNames = new Set();
      const now = new Date();

      // 步骤 1: 确定状态更改并识别新的故障设备 (用于高亮和动画)
      this.uniqueLatheNames.forEach(latheName => {
        const summary = this.latheNameSummaries[latheName];
        const newStatus = summary ? summary.status : '离线';
        const oldStatus = this.previousLatheNameStatuses[latheName];

        if (oldStatus !== undefined && newStatus !== oldStatus) {
          if (newStatus === '故障' && oldStatus !== '故障') {
            localNewlyFaultyLatheNames.add(latheName);

            // 弹出全局 Toast，并记录
            if (!this.lastNotifiedFaults.has(latheName)) {
              this.$notify({
                title: '故障告警',
                message: `${latheName} 故障，立即问询 AI`,
                type: 'error',
                duration: 5000,
                onClick: () => {
                  this.inquiryFromLog({ deviceName: latheName });
                }
              });
              this.lastNotifiedFaults.add(latheName);
            }

            // 记录状态变为故障的时间点，用于显示上次正常时间
            if (summary) {
              summary.lastNormalTime = now.toISOString();
            }
          }

          // 若故障恢复，移除已通知标记
          if (oldStatus === '故障' && newStatus !== '故障') {
            this.lastNotifiedFaults.delete(latheName);
          }

          // 将需要播放状态变化动画的设备添加到集合中
          this.latheNamesToAnimate.add(latheName);

          // 设置动画持续时间为1秒，延迟后移除动画标记
          setTimeout(() => {
            this.latheNamesToAnimate.delete(latheName);
          }, 1000);
        }

        // 更新状态记录
        this.previousLatheNameStatuses[latheName] = newStatus;
      });

      // 更新新故障设备集合
      this.newlyFaultyLatheNames = localNewlyFaultyLatheNames;

      // 步骤 2: 为所有唯一的车床名称创建日志条目
      let allPossibleLogs = this.uniqueLatheNames.map(latheName => {
        const summary = this.latheNameSummaries[latheName];
        const status = summary ? summary.status : '离线';
        const collectTime = summary ? summary.collectTime : new Date().toISOString();

        return {
          deviceName: latheName,
          time: new Date(collectTime).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' }),
          type: status,
          isNewAlarm: this.newlyFaultyLatheNames.has(latheName),
        };
      });

      // 步骤 3: 对所有日志按设备名称排序，确保轮播顺序稳定
      allPossibleLogs.sort((a, b) => {
        return a.deviceName.localeCompare(b.deviceName);
      });

      // 步骤 4: 使用滑动窗口截取要显示的日志
      const displayCount = 8;
      if (allPossibleLogs.length === 0) {
        this.monitorLogs = [];
        return;
      }

      if (this.monitorLogDisplayOffset >= allPossibleLogs.length) {
        this.monitorLogDisplayOffset = 0;
      }

      const itemsToShow = [];
      for (let i = 0; i < displayCount; i++) {
        if (allPossibleLogs.length === 0) break;
        const index = (this.monitorLogDisplayOffset + i) % allPossibleLogs.length;
        if (allPossibleLogs[index]) { // Ensure the item exists
          itemsToShow.push(allPossibleLogs[index]);
        }
      }
      this.monitorLogs = itemsToShow;

      // 步骤 5: 更新偏移量，为下一次轮播做准备
      if (allPossibleLogs.length > 0) { // Only advance offset if there are logs
        this.monitorLogDisplayOffset = (this.monitorLogDisplayOffset + 1) % allPossibleLogs.length;
      } else {
        this.monitorLogDisplayOffset = 0; // Reset if list becomes empty
      }

      // 步骤 6: 滚动到顶部 (已注释掉)
      /*
            this.$nextTick(() => {
                const logListElement = this.$el.querySelector('.log-list');
                if (logListElement) {
                    logListElement.scrollTop = 0;
                }
            });
            */
    },
    startAutoDeviceHover() {
      this.stopAutoDeviceHover(); // 先清除已有的定时器
      if (this.uniqueLatheNames && this.uniqueLatheNames.length > 0) {
        // 立即显示下一个（或第一个）
        this.showNextAutoHoveredDevice();

        // 启动增强版的轮播间隔
        this.autoHoverTimer = setInterval(() => {
          // 如果有故障设备，减少轮播间隔以更频繁展示故障设备
          const hasWarning = Object.values(this.latheNameSummaries).some(summary =>
            summary && summary.status === '故障'
          );

          // 根据是否有故障设备动态调整间隔
          if (hasWarning) {
            // 在有故障设备时，调整为更短的间隔（3秒）
            this.autoHoverInterval = 3000;
          } else {
            // 在无故障设备时，恢复默认间隔（5秒）
            this.autoHoverInterval = 5000;
          }

          this.showNextAutoHoveredDevice();
        }, this.autoHoverInterval);
      }
    },
    showNextAutoHoveredDevice()
    {
      if (!this.uniqueLatheNames || this.uniqueLatheNames.length === 0) {
        this.autoHoverDeviceName = null;
        return;
      }

      // 先清除当前的悬浮设备
      this.autoHoverDeviceName = null;

      // 短暂延迟后设置新的悬浮设备，创造出连续悬浮之间的过渡间隔
      setTimeout(() => {
        this.currentAutoHoverIndex = (this.currentAutoHoverIndex + 1) % this.uniqueLatheNames.length;

        // 智能选择设备 - 优先显示故障设备
        let priorityIndex = -1;

        // 首先寻找故障设备
        if (this.currentAutoHoverIndex === 0) { // 仅在轮回开始时检查，避免频繁计算
          for (let i = 0; i < this.uniqueLatheNames.length; i++) {
            const latheName = this.uniqueLatheNames[i];
            const summary = this.latheNameSummaries[latheName];
            if (summary && summary.status === '故障') {
              priorityIndex = i;
              break;
            }
          }

          // 如果找到故障设备，设置为当前索引
          if (priorityIndex !== -1) {
            this.currentAutoHoverIndex = priorityIndex;
          }
        }

        this.autoHoverDeviceName = this.uniqueLatheNames[this.currentAutoHoverIndex];

        // 智能定位算法 - 确保悬浮框在视口内
        this.$nextTick(() => {
          const deviceItem = document.querySelector(`.device-item.auto-hover-active`);
          const tooltip = document.querySelector(`.device-tooltip.auto-tooltip-active`);

          if (deviceItem && tooltip) {
            deviceItem.getBoundingClientRect();
            const tooltipRect = tooltip.getBoundingClientRect();
            const viewportWidth = window.innerWidth;
// 检查提示框是否溢出左侧或右侧视口
            if (tooltipRect.left < 20) { // 左侧留20px边距
              // 如果溢出左侧，调整定位
              tooltip.style.left = '20px';
              tooltip.style.transform = 'translateX(0) translateY(0) perspective(600px) rotateX(0)';
              this.tooltipPositionAdjusted = true;
            } else if (tooltipRect.right > viewportWidth - 20) { // 右侧留20px边距
              // 如果溢出右侧，调整定位
              tooltip.style.left = 'auto';
              tooltip.style.right = '20px';
              tooltip.style.transform = 'translateX(0) translateY(0) perspective(600px) rotateX(0)';
              this.tooltipPositionAdjusted = true;
            } else if (tooltipRect.top < 20) { // 顶部留20px边距
              // 如果溢出顶部，调整为底部显示
              tooltip.style.bottom = 'auto';
              tooltip.style.top = 'calc(100% + 20px)';
              // 修改三角形方向
              tooltip.classList.add('position-bottom');
              this.tooltipPositionAdjusted = true;
            } else {
              // 重置调整标记
              this.tooltipPositionAdjusted = false;
            }

            // 检查是否为故障设备，添加额外信息
            const latheName = this.uniqueLatheNames[this.currentAutoHoverIndex];
            const summary = this.latheNameSummaries[latheName];
            if (summary && summary.status === '故障') {
              // 为故障设备添加额外信息
              this.lastHoveredWarningDevice = latheName;
              if (document.fullscreenElement) { // 仅全屏模式显示额外信息
                tooltip.setAttribute('data-extra-info', `上次正常时间: ${new Date(summary.lastNormalTime || Date.now() - 3600000).toLocaleTimeString()}`);
              }
            } else if (this.lastHoveredWarningDevice) {
              // 清除之前设置的故障设备信息
              tooltip.removeAttribute('data-extra-info');
              this.lastHoveredWarningDevice = null;
            }
          }
        });
      }, 200);
    }
    ,
    stopAutoDeviceHover() {
      if (this.autoHoverTimer) {
        clearInterval(this.autoHoverTimer);
        this.autoHoverTimer = null;
      }
      // 当手动停止时，不立即清除autoHoverDeviceName，让当前悬浮的消失有一个自然的过渡（通过下一次轮播或鼠标移开）
    },
    handleDeviceItemMouseEnter() {
      this.stopAutoDeviceHover();
      this.autoHoverDeviceName = null; // 清除自动悬浮的目标，让CSS hover生效
    },
    handleDeviceItemMouseLeave() {
      // 鼠标移开后，延迟一小段时间再重新启动自动悬浮，避免与快速划过冲突
      setTimeout(() => {
        // 检查鼠标是否真的移出了所有device-item，避免在项目间移动时频繁启停
        const hoveredItem = document.querySelector('.device-item:hover');
        if (!hoveredItem) {
          this.startAutoDeviceHover();
        }
      }, 300);
    },
    // 跳转到问询页并携带设备ID，直接触发AI分析
    goToInquiry() {
      if (this.currentDevice && this.currentDevice.id) {
        const deviceId = this.currentDevice.id;
        const deviceData = this.deviceAccelerationData[deviceId] || {};

        // 构造完整的 sensorData 对象
        const sensorData = {
          deviceName: this.currentDevice.latheName || '',
          sensorId: deviceId,
          position: this.currentPosition || '',
          // 假设温度数据在 deviceAccelerationData[deviceId].temperature，如果不是请调整
          temperature: deviceData.temperature !== undefined ? deviceData.temperature : 0,
          rmsX: deviceData.rms?.x || [],
          rmsY: deviceData.rms?.y || [],
          rmsZ: deviceData.rms?.z || [],
          peakX: deviceData.peak?.x || [],
          peakY: deviceData.peak?.y || [],
          peakZ: deviceData.peak?.z || []
        };

        this.$router.push({
          path: '/gelly/inquiry',
          query: {
            sensorId: deviceId,
            latheName: this.currentDevice.latheName || '',
            axis: this.currentPosition || '',
            // 将 sensorData 对象 JSON.stringify 后再进行 encodeURIComponent 编码
            data: encodeURIComponent(JSON.stringify(sensorData)),
            // 新增：标记需要自动触发AI分析
            autoAnalyze: 'true'
          }
        });
      }
    },
    buildInquiryDesc(deviceId) {
      const status = this.getDeviceStatus(deviceId);
      const summary = this.latheNameSummaries[this.currentDevice.latheName] || {};
      const time = summary.collectTime ? new Date(summary.collectTime).toLocaleTimeString() : new Date().toLocaleTimeString();

      // 取最近 6 个点（约 1 分钟）RMS X/Y/Z
      const deviceData = this.deviceAccelerationData[deviceId];
      let rmsStr = '';
      if (deviceData && deviceData.rms) {
        const take = 6;
        const lastX = deviceData.rms.x.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
        const lastY = deviceData.rms.y.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
        const lastZ = deviceData.rms.z.slice(-take).filter(v=>v).map(v=>v.toFixed(2));
        rmsStr = `最近${take}点 RMS(X/Y/Z): ${lastX.join(',')} / ${lastY.join(',')} / ${lastZ.join(',')}`;
      }
      return `${status} 状态，采样时间 ${time}。${rmsStr}`;
    },
    // 从监测记录跳转问询
    inquiryFromLog(log) {
      if (!log || !log.deviceName) return;
      let deviceId = null;
      // 优先从 latheNameToDeviceMap 获取
      if (this.latheNameToDeviceMap[log.deviceName] && this.latheNameToDeviceMap[log.deviceName].length > 0) {
        deviceId = this.latheNameToDeviceMap[log.deviceName][0];
      } else {
        // 退而求其次，遍历 deviceStatusData
        const dev = this.deviceStatusData.find(d => d.latheName === log.deviceName);
        if (dev) deviceId = dev.deviceId;
      }
      if (deviceId) {
        const query = {
          sensorId: deviceId,
          latheName: log.deviceName || '',
        };
        if (log.axis) query.axis = log.axis; // 若后续日志带 axis
        query.desc = this.buildInquiryDesc(deviceId);
        this.$router.push({ path: '/gelly/inquiry', query });
      } else {
        this.$message.warning('无法定位该设备编号');
      }
    },
  },
  watch: {
    deviceStatusData: {
      handler(newData) {
        console.log('设备数据已更新:', newData)
        // 可以在这里添加数据变化的处理逻辑
      },
      deep: true
    }
  }
}
</script>


<style lang="scss" scoped>
.index {
  width: 100%;
  height: 100vh;
  // 修改背景图片路径写法
  background: url('../../../assets/detect/background.jpg') no-repeat center center;
  background-size: cover;
  color: #fff;
  overflow: hidden;
  display: flex;

  &.fullscreen-mode {
    // 同步修改全屏模式下的背景图片路径
    background: url('../../../assets/detect/background.jpg') no-repeat center center;
    background-size: cover;

    .dashboard {
      width: 100vw;
      height: 100vh;
      padding: 0;
    }

  }
}

.left-sidebar {
  &.hidden {
    display: none;
  }
}

// 全屏时的样式
:fullscreen,
:-webkit-full-screen,
:-moz-full-screen,
:-ms-fullscreen {
  .index {
    // 同步修改其他全屏模式下的背景图片路径
    background: url('../../../assets/detect/background.jpg') no-repeat center center;
    background-size: cover;
  }
}

.dashboard {
  position: relative; // 添加这行
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  flex-direction: column;
}

.header {
  height: 54px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: transparent; // 移除底色

  .title-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 5px;
    flex: 1;

    h1 {
      margin-top: 15px;
      font-size: 35px; // 增大标题字号
      font-weight: 500;
      color: #fff;
      letter-spacing: 1px;
    }

    .tabs {
      display: flex;
      gap: 2px;
      justify-content: center;

      .tab {
        padding: 2px 12px;
        font-size: 12px;
        color: #fff;
        cursor: pointer;
        background: rgba(0, 60, 120, 0.5);
        border-radius: 10px;

        &.active {
          background: rgba(0, 120, 255, 0.3);
        }

        &:hover {
          background: rgba(0, 120, 255, 0.2);
        }
      }
    }
  }

  .status-legend {
    display: flex;
    gap: 15px;
    min-width: 180px;

    &.left {
      justify-content: flex-start;
    }

    &.right {
      justify-content: flex-end;
    }

    .legend-item {
      display: flex;
      align-items: center;
      font-size: 12px;
      color: #8f9bb3;
      white-space: nowrap;

      .dot {
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 5px;

        &.normal {
          background: #00ff00;
        }

        &.waiting {
          background: #ff9900;
        }

        &.warning {
          background: #ff0000;
        }

        &.offline {
          background: #666666;
        }
      }
    }
  }
}

.content {
  display: grid;
  grid-template-columns: 22% 54% 22%;
  grid-template-rows: 60% 38%; /* 调整行高比例，增加底部行高 */
  gap: 20px;
  padding: 0 15px 0 5px; /* 减小底部内边距 */
  height: calc(100vh - 64px); /* 调整整体高度 */
}

// 左侧统计和监测模块
.left-module {
  grid-column: 1;
  grid-row: 1 / span 2;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 10px; // 减小底部内边距

  //设备使用率统计模块
  //背景框架
  .stat-card {
    height: calc(25% - 6px);
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid #1c599c4d;
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    .stat-content {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      height: calc(100% - 40px); // 减去标题高度

      .circle-progress {
        width: 100%; // 使用百分比宽度
        height: 100%; // 使用百分比高度
        flex-shrink: 0;
        background: transparent;
      }

      // 移除旧的图例样式
      .stat-legend {
        display: none;
      }
    }
  }

  .usage-chart {
    height: calc(25% - 6px);
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden; // 添加overflow控制

    .chart-title {
      height: 40px;
      padding: 0 20px;
      font-size: 17px;
      color: #fff;
      display: flex;
      align-items: center;
      position: relative;
    }

    #usageChart {
      flex: 1;
      height: calc(100% - 40px) !important; // 减去标题高度
      min-height: 0; // 防止内容溢出
      padding: 10px; // 添加内边距
    }
  }

  // 传感器运行状态模块
  .comparison-chart {
    height: calc(25% - 6px);
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    .chart-content {
      flex: 1;
      display: flex; // 添加flex布局
      align-items: center; // 垂直居中
      justify-content: center; // 水平居中
      padding: 0 20px; // 添加左右内边距

      #comparisonChart {
        width: 50% !important; // 设置图表宽度为50%
        height: 100% !important;
        display: flex;
        align-items: center;
      }

      .status-text {
        width: 50%; // 设置文字区域宽度为50%
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: flex-start;
        padding-left: 20px;

        .title {
          font-size: 24px;
          color: #fff;
          margin-bottom: 10px;
        }

        .subtitle {
          font-size: 16px;
          color: #8f9bb3;
          margin-bottom: 5px;
        }
      }
    }
  }

  .monitor-log {
    height: calc(50% - 12px); // 修改高度以占据更大空间
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden; // 添加此行，确保内容溢出时能正确处理

    .log-list {
      flex: 1;
      padding: 10px;
      display: flex; // 修改为flex，以便wrapper可以控制内部项
      flex-direction: column;
      // gap: 8px; // gap移到wrapper或由margin控制
      overflow-y: hidden; // 改为hidden，滚动由内部wrapper或动画控制
      position: relative; // 为动画定位提供上下文
      perspective: 1000px; // 为3D旋转动画添加透视

      .log-items-wrapper {
        display: flex;
        flex-direction: column;
        gap: 8px; // 项目之间的间距
        width: 100%;
      }

      // 添加自定义滚动条样式（可选，但推荐）
      // For Webkit browsers (Chrome, Safari, Edge)
      &::-webkit-scrollbar {
        width: 5px; // 使滚动条更细一点
      }
      &::-webkit-scrollbar-track {
        background: rgba(255,255,255,0.02); // 使轨道更透明
        border-radius: 3px;
      }
      &::-webkit-scrollbar-thumb {
        background: rgba(255,255,255,0.25); // 滑块颜色稍微加深一点点
        border-radius: 3px;
        &:hover {
          background: rgba(255,255,255,0.4);
        }
      }
      // For Firefox
      scrollbar-width: thin; // "auto" or "thin"
      scrollbar-color: rgba(255,255,255,0.25) rgba(255,255,255,0.02); // thumb color and track color

      .log-item {
        display: flex;
        align-items: center;
        padding: 12px 18px; /* 调整内边距 */
        background: rgba(10, 25, 60, 0.75); /* 卡片背景色 */
        /* border-bottom: 1px dashed rgba(143, 155, 179, 0.1); */ /* 移除下划线 */
        border-radius: 8px; /* 圆角 */
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25); /* 卡片阴影 */
        transition: background-color 0.3s ease, border-left 0.3s ease, transform 0.3s ease; /* 为手动悬浮/高亮添加transform过渡 */

        .status-tag {
          padding: 4px 10px; // 从 2px 8px 调整为 4px 10px
          border-radius: 4px;
          font-size: 12px;
          margin-right: 15px; // 从 30px 调整为 15px
          min-width: auto; // 移除固定最小宽度，让其自适应内容
          text-align: center;
          white-space: nowrap; // 防止标签内文字换行

          &.normal {
            background: #20b84e;
            color: #ffffff;
          }

          &.warning {
            background: #ff2b2b;
            color: #ffffff;
          }

          &.waiting {
            background: #ffb300;
            color: #ffffff;
          }

          &.offline {
            background: #808080;
            color: #ffffff;
          }
        }

        .log-content {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 10px;

          .device-name {
            color: #8f9bb3;
            font-size: 14px;
          }
        }

        .log-time {
          color: #8f9bb3;
          font-size: 14px;
        }

        &.new-alarm-highlight {
          background-color: rgba(255, 43, 43, 0.15); // 与故障标签背景略有不同的背景色
          border-left: 3px solid #ff2b2b; // 为告警添加显眼的左边框

        }

        /* AI 问询按钮样式 */
        .ai-log-btn {
          margin-left: 10px;
          width: 22px;
          height: 22px;
          border-radius: 50%;
          background: rgba(255, 43, 43, 0.25);
          display: flex;
          align-items: center;
          justify-content: center;
          color: #ff2b2b;
          cursor: pointer;
          animation: aiPulse 1.2s infinite ease-in-out;
          transition: background 0.3s;

          i {
            font-size: 14px;
          }

          &:hover {
            background: rgba(255, 43, 43, 0.35);
          }
        }
      }
    }
  }
}

// 中间设备网格模块
.center-module {
  grid-column: 2;
  grid-row: 1;
  display: flex;
  flex-direction: column;
  justify-content: center; // 垂直居中
  align-items: center; // 水平居中

  // 修改现有样式以适应新增的按钮组
  position: relative;

  .workshop-buttons {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 10;
    transform: rotate(0deg);

    .switch-buttons {
      display: flex;
      gap: 6px; // 减小按钮间距

      .switch-btn {
        padding: 3px 10px; // 减小内边距
        border: 1px solid rgba(255, 255, 255, 0.6);
        border-radius: 4px;
        background: transparent;
        color: rgba(255, 255, 255, 0.6);
        cursor: pointer;
        font-size: 12px; // 减小字体大小
        transition: all 0.3s ease;
        min-width: 60px; // 减小最小宽度
        text-align: center;

        &:hover {
          border-color: #fff;
          color: #fff;
          background: rgba(255, 255, 255, 0.1);
        }

        &.active {
          background: rgba(255, 255, 255, 0.1);
          border-color: #fff;
          color: #fff;
        }
      }
    }
  }

  .device-grid {
    width: 675px;
    height: 655px;
    margin: auto;
    background: transparent;
    border: none;
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    grid-template-rows: repeat(5, 1fr);
    gap: 0;
    transform: rotate(328deg) scale(0.70); // 正常模式下缩放比例为1
    transform-origin: center;

    .device-item {
      position: relative;
      background: transparent;
      border: none;
      width: 93px;
      height: 99px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      transform: rotate(-330deg);
      margin: 0;

      // 第一行保持原位
      &:nth-child(-n+7) {
        top: 50px;
        left: -130px;
      }

      // 第二行设备向上移动
      &:nth-child(n+8):nth-child(-n+14) {
        top: 20px;
        left: -80px;
      }

      // 第三行设备向上移动更多
      &:nth-child(n+15):nth-child(-n+21) {
        top: -10px;
        left: -10px;
      }

      // 第四行设备向上移动
      &:nth-child(n+22):nth-child(-n+28) {
        top: -50px;
        left: 50px;
      }

      // 第五行设备向上移动最多
      &:nth-child(n+29):nth-child(-n+35) {
        top: -90px;
        left: 120px;
      }

      // 保持原有的行间距设置
      &:nth-child(1),
      &:nth-child(2),
      &:nth-child(3),
      &:nth-child(8),
      &:nth-child(9),
      &:nth-child(10),
      &:nth-child(15),
      &:nth-child(16),
      &:nth-child(17),
      &:nth-child(18),
      &:nth-child(19),
      &:nth-child(20),
      &:nth-child(21),
      &:nth-child(22),
      &:nth-child(23),
      &:nth-child(26),
      &:nth-child(27),
      &:nth-child(28),
      &:nth-child(33),
      &:nth-child(34),
      &:nth-child(35) {
        margin: 0 0 55px 0;
      }

      .device-icon {
        width: 85px;
        height: 85px;
        display: flex;
        justify-content: center;
        align-items: center;
        transition: transform 0.3s ease-in-out; // 为手动悬浮时的放大做准备

        img {
          width: 100%;
          height: 100%;
          object-fit: contain;
          // 初始状态，动画会在这里应用
        }
      }

      // 添加悬浮提示框样式
      .device-tooltip {
        display: none;
        position: absolute;
        bottom: 130%;
        left: 50%;
        transform: translateX(-50%) translateY(10px) perspective(600px) rotateX(5deg);
        padding: 16px 20px;
        border-radius: 12px;
        font-size: 14px;
        line-height: 1.6;
        white-space: nowrap;
        z-index: 1000;
        pointer-events: none;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 10px rgba(255, 255, 255, 0.1) inset;
        min-width: 200px;
        opacity: 0; // 初始状态为透明
        transition: all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1); // 使用弹性缓动函数
        visibility: hidden; // 初始状态为不可见，配合opacity实现动画
        backdrop-filter: blur(8px); // 毛玻璃效果
        -webkit-backdrop-filter: blur(8px);
        border: 1px solid rgba(255, 255, 255, 0.18);
        overflow: hidden; // 防止内部元素溢出
        transform-origin: bottom center;

        // 添加背景动态光效
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.1), transparent 80%);
          opacity: 0.8;
          z-index: -1;
          transition: opacity 0.3s ease;
        }

        // 新增：自动悬浮激活时的样式
        &.auto-tooltip-active {
          display: block;
          opacity: 1;
          visibility: visible;
          transform: translateX(-50%) translateY(0) perspective(600px) rotateX(0);
          animation: tooltip-pulse 2s infinite alternate ease-in-out;
        }

        // 根据状态改变整个提示框的颜色和效果
        &.normal {
          background: linear-gradient(135deg, rgba(32, 184, 78, 0.85), rgba(32, 184, 78, 0.6));
          border: 1px solid rgba(32, 184, 78, 0.6);
          color: #ffffff;
          box-shadow: 0 8px 32px rgba(32, 184, 78, 0.3), 0 0 15px rgba(32, 184, 78, 0.2);
        }

        &.warning {
          background: linear-gradient(135deg, rgba(255, 43, 43, 0.85), rgba(255, 43, 43, 0.6));
          border: 1px solid rgba(255, 43, 43, 0.6);
          color: #ffffff;
          box-shadow: 0 8px 32px rgba(255, 43, 43, 0.3), 0 0 15px rgba(255, 43, 43, 0.2);
        }

        &.waiting {
          background: linear-gradient(135deg, rgba(255, 179, 0, 0.85), rgba(255, 179, 0, 0.6));
          border: 1px solid rgba(255, 179, 0, 0.6);
          color: #ffffff;
          box-shadow: 0 8px 32px rgba(255, 179, 0, 0.3), 0 0 15px rgba(255, 179, 0, 0.2);
        }

        &.offline {
          background: linear-gradient(135deg, rgba(128, 128, 128, 0.85), rgba(128, 128, 128, 0.6));
          border: 1px solid rgba(128, 128, 128, 0.6);
          color: #ffffff;
          box-shadow: 0 8px 32px rgba(128, 128, 128, 0.3), 0 0 15px rgba(128, 128, 128, 0.2);
        }

        // 修改小三角样式，根据状态改变颜色
        &::after {
          content: '';
          position: absolute;
          top: 100%;
          left: 50%;
          transform: translateX(-50%);
          border: 10px solid transparent;
          filter: drop-shadow(0 4px 4px rgba(0, 0, 0, 0.2));
          transition: all 0.3s ease;
        }

        // 当提示框位置在设备图标下方时，三角形朝上
        &.position-bottom::after {
          top: auto;
          bottom: 100%;
          border-top-color: transparent;
          border-bottom-color: inherit;
        }

        &.normal::after {
          border-top-color: rgba(32, 184, 78, 0.8);
        }

        &.warning::after {
          border-top-color: rgba(255, 43, 43, 0.8);
        }

        &.waiting::after {
          border-top-color: rgba(255, 179, 0, 0.8);
        }

        &.offline::after {
          border-top-color: rgba(128, 128, 128, 0.8);
        }

        // 内容样式改进
        span {
          display: block;
          margin: 4px 0;
          font-weight: 600;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); // 添加文字阴影

          &:first-child {
            margin-top: 0;
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);
            padding-bottom: 8px;
            text-align: center;
            letter-spacing: 0.5px; // 增加字间距
          }

          &.status-line {
            margin-top: 8px;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;

            // 添加状态图标
            &::before {
              content: '';
              display: inline-block;
              width: 8px;
              height: 8px;
              border-radius: 50%;
              margin-right: 8px;
            }
          }

          &:last-child {
            margin-bottom: 0;
          }
        }

        // 状态图标颜色
        &.normal .status-line::before {
          background-color: #ffffff;
          box-shadow: 0 0 8px #ffffff;
        }

        &.warning .status-line::before {
          background-color: #ffffff;
          box-shadow: 0 0 8px #ffffff;
          animation: blink 1s infinite;
        }

        &.waiting .status-line::before {
          background-color: #ffffff;
          box-shadow: 0 0 8px #ffffff;
        }

        &.offline .status-line::before {
          background-color: rgba(255, 255, 255, 0.6);
        }
      }

      // 添加鼠标悬浮时显示提示框的样式
      &:hover {
        .device-tooltip {
          display: block;
          opacity: 1;
          visibility: visible;
          transform: translateX(-50%) translateY(0) perspective(600px) rotateX(0);
          // 手动悬浮时添加更丰富的动画
          animation: tooltip-entrance 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
        }
        // 手动悬浮时，图标放大，并移除可能存在的呼吸动画（如果需要更强的区分）
        .device-icon {
          transform: scale(1.15);
          filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.6));
          transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
          img {
            animation: none; // 停止呼吸动画，确保手动悬浮效果优先
          }
        }
      }

      // 当设备被自动轮播选中时，应用呼吸动画
      &.auto-hover-active {
        .device-icon img {
          animation: breathingEffect 2s ease-in-out infinite;
        }

        // 当提示框激活时，确保图标明显地高亮
        &:hover .device-icon {
          transform: scale(1.15);
          filter: drop-shadow(0 0 8px rgba(255, 255, 255, 0.5));
        }
      }
    }
  }
}

// 定义动画
@keyframes breathingEffect {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.08);
    opacity: 0.8;
  }
}

@keyframes tooltip-pulse {
  0% {
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3), 0 0 10px rgba(255, 255, 255, 0.1) inset;
  }
  100% {
    box-shadow: 0 8px 32px rgba(255, 255, 255, 0.15), 0 0 15px rgba(255, 255, 255, 0.2) inset;
  }
}

@keyframes blink {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

@keyframes tooltip-entrance {
  0% {
    transform: translateX(-50%) translateY(15px) perspective(600px) rotateX(10deg);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  70% {
    transform: translateX(-50%) translateY(-5px) perspective(600px) rotateX(-2deg);
  }
  100% {
    transform: translateX(-50%) translateY(0) perspective(600px) rotateX(0);
  }
}

// 新增：状态标签变化动画
@keyframes statusChangePulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.1);
  }
  50% {
    transform: scale(1.15);
    box-shadow: 0 0 8px 10px rgba(255, 255, 255, 0.05); // 轻微的白色外发光
  }
  100% {
    transform: scale(1);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0);
  }
}

.status-tag.status-change-animate {
  animation: statusChangePulse 0.8s ease-out forwards;
  // `forwards` 会让动画停在最后一帧，如果希望动画后恢复原样，可以去掉forwards，并确保js中移除class的时机准确
  // 或者动画本身设计成回到原点，然后js移除class
}

// 右上评分和运行率模块
.right-top-module {
  grid-column: 3;
  grid-row: 1;
  display: flex;
  flex-direction: column;
  gap: 15px; // 增加评分和运行率之间的间距

  .health-score {
    height: calc(50% - 7.5px);
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    .score-content {
      flex: 1;
      display: flex;
      flex-direction: column; // 改为纵向排列
      align-items: center; // 水平居中
      justify-content: flex-start; // 从顶部开始排列
      padding: 10px 20px;

      .score-circle {
        width: 180px;
        height: 180px;
        margin-top: 5px; // 减小顶部间距
        margin-bottom: 15px; // 减小底部间距
      }

      .score-details {
        width: 100%;
        text-align: center;

        .detail-item {
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
          margin-bottom: 5px;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  .running-rate {
    height: calc(50% - 7.5px);
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;


    .chart {
      flex: 1;
      padding: 10px; // 减小内边距以增加图表可用空间
      height: calc(100% - 40px); // 确保图表占满剩余空间
    }
  }
}
.data-status {
  position: absolute; // 改为绝对定位
  top: 15px;
  right: 15px;
  padding: 8px 15px;
  background: rgba(0, 0, 0, 0.3);
  color: #8f9bb3;
  border-radius: 10px;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 12px;
  backdrop-filter: blur(4px);
  transition: all 0.3s ease;
  z-index: 1000;

  .updating-dot {
    width: 8px;
    height: 8px;
    background: #00a0e9;
    border-radius: 50%;
    animation: pulse 1s infinite;
  }

  .fullscreen-btn {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #8f9bb3;
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    margin-left: 12px;
    transition: all 0.3s ease;

    &:hover {
      color: #fff;
      background: rgba(0, 120, 255, 0.2);
      transform: scale(1.05);
    }

    i {
      font-size: 18px;
    }
  }
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.5;
  }

  50% {
    transform: scale(1.2);
    opacity: 1;
  }

  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
}

@media screen and (min-width: 1280px) and (min-height: 720px) {
  .dashboard {
    min-width: 1280px;
    min-height: 720px;
  }
}

@media screen and (max-height: 900px) {
  .header {
    height: 50px;

    h1 {
      font-size: 40px;
    }

    .tabs .tab {
      padding: 1px 10px;
    }
  }

  .chart {
    height: 150px;
  }

  .circle-progress {
    width: 100px;
    height: 100px;
  }
}

// 修改全屏样式混入
@mixin fullscreen-styles {
  background: url('../../../assets/detect/background.jpg') no-repeat center center !important;
  background-size: cover !important;

  .dashboard {
    height: 100vh !important;
    width: 100vw !important;
    padding: 15px;
    margin: 0;

    .content {
      display: grid;
      grid-template-columns: 22% 54% 22%;
      grid-template-rows: 68% 30%; // 保持网格比例
      gap: 20px;
      padding: 0 15px;
      height: calc(100vh - 54px);

    }
  }

  .circle-progress {
    &::after {
      background: rgb(3, 12, 49); // 使用相同的深蓝色背景
    }
  }

  .health-score {
    .score-content {
      .score-circle {
        width: 180px;
        height: 180px;
        margin-left: 30px;
        margin-top: 10px; // 减小顶部间距
        margin-bottom: 20px;
      }

      .score-details {
        margin-left: 20px;
        margin-top: -70px;

        .detail-item {
          font-size: 16px;
          margin-bottom: 5px;
        }
      }
    }
  }

  .header {
    .title-section {
      h1 {
        font-size: 48px; // 增大字号
        margin-top: 40px; // 增加顶部间距
        margin-bottom: 20px; // 添加底部间距

      }
    }
  }

  .comparison-chart {
    #comparisonChart {
      transform: scale(1.2);
      transform-origin: center; // 从中心点放大
      margin-top: 30px !important; // 适当下移以保持居中
      margin-left: 7px !important;

      .gauge-detail {
        .rich-text {
          .title {
            font-size: 22px !important; // 放大标题文字
            padding: 0 0 20px 0;
          }

          .value {
            font-size: 42px !important; // 放大数值文字
            padding: 0 0 20px 0;
          }

          .device {
            font-size: 20px !important; // 放大设备数量文字
          }
        }
      }
    }
  }

  .comparison-chart {
    .chart-content {
      padding: 0 40px; // 全屏模式下增加内边距

      #comparisonChart {
        transform: scale(1.2);
        transform-origin: center;
      }

      .status-text {
        padding-left: 40px; // 全屏模式下增加文字区域的左边距

        .title {
          font-size: 28px; // 全屏模式下增大字号
        }

        .subtitle {
          font-size: 18px; // 全屏模式下增大字号
        }
      }
    }
  }


  .center-module {
    .device-grid {
      width: 605px;
      height: 605px;
      transform: rotate(328deg) scale(0.85);
      transform-origin: center;
      // 向下移动
      // 向右移动
      margin: 20px auto auto 130px;

      // 调整设备图标在全屏模式下的位置
      .device-item {

        // 第一行位置调整
        &:nth-child(-n+7) {
          top: 60px; // 调整顶部距离
          left: -140px; // 调整左侧距离
        }

        // 第二行位置调整
        &:nth-child(n+8):nth-child(-n+14) {
          top: 30px;
          left: -90px;
        }

        // 第三行位置调整
        &:nth-child(n+15):nth-child(-n+21) {
          top: 0;
          left: -20px;
        }

        // 第四行位置调整
        &:nth-child(n+22):nth-child(-n+28) {
          top: -40px;
          left: 40px;
        }

        // 第五行位置调整
        &:nth-child(n+29):nth-child(-n+35) {
          top: -80px;
          left: 110px;
        }
      }
    }
  }
}

// 应用全屏样式到各个浏览器
:fullscreen {
  @include fullscreen-styles;
}

:-webkit-full-screen {
  @include fullscreen-styles;
}

:-moz-full-screen {
  @include fullscreen-styles;
}

:-ms-fullscreen {
  @include fullscreen-styles;
}

// 全屏按钮样式
.fullscreen-btn {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #8f9bb3;
  background: rgba(3, 12, 49, 0.6);
  border: 1px solid rgba(28, 89, 156, 0.3);
  border-radius: 10px;
  margin-left: 12px;
  transition: all 0.3s ease;

  &:hover {
    color: #fff;
    background: rgba(0, 120, 255, 0.2);
    transform: scale(1.05);
  }

  i {
    font-size: 18px;
  }
}

// 统一的标题样式
.chart-title {
  left: 10px;
  height: 40px; // 增加高度
  padding: 0 20px; // 增加左右内边距
  font-size: 17px; // 调整字体大小
  color: #fff; // 改为白色
  display: flex;
  align-items: center;
  position: relative; // 为左侧装饰做准备

  // 左侧装饰条
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 16px;
    background: #ff9900; // 橙色装饰条
    border-radius: 0 2px 2px 0;
  }
}

// 调整各个模块的标题样式
.stat-card,
.usage-chart,
.comparison-chart,
.monitor-log,
.acceleration-chart,
.health-score,
.running-rate,
.shift-rate,

  // 加速度数据图表的标题样式调整
.acceleration-chart .chart-title {
  justify-content: space-between; // 两端对齐，因为右侧有状态显示

  .device-status {
    font-size: 12px;
    padding: 2px 12px;
    border-radius: 10px;
    background: rgba(0, 0, 0, 0.2);
  }
}

// 调整图表容器，为新的标题高度做适配
.chart-content,
#accelerationChart,
#comparisonChart,
#usageChart,

.acceleration-chart {
  position: relative; // 添加相对定位

  .chart-title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chart-controls {
      display: flex;
      align-items: center;
      gap: 15px;

      .switch-buttons {
        display: flex;
        gap: 8px;

        .switch-btn {
          padding: 4px 12px;
          border: 1px solid rgba(255, 255, 255, 0.6);
          border-radius: 4px;
          background: transparent;
          color: rgba(255, 255, 255, 0.6);
          cursor: pointer;
          font-size: 12px;
          transition: all 0.3s ease;
          min-width: 60px;
          text-align: center;

          &:hover {
            border-color: #fff;
            color: #fff;
          }

          &.active {
            background: rgba(255, 255, 255, 0.1);
            border-color: #fff;
            color: #fff;
          }
        }
      }
    }
  }
}

// 其他浏览器全屏样式
:-webkit-full-screen,
:-moz-full-screen,
.acceleration-chart {
  .chart-title {
    .chart-controls {
      .device-status {
        &.normal {
          background: rgba(0, 255, 76, 0.2); // 正常状态 - 绿色背景
          color: #00ff4c;
        }

        &.warning {
          background: rgba(255, 43, 43, 0.2); // 故障状态 - 红色背景
          color: #ff2b2b;
        }

        &.waiting {
          background: rgba(255, 179, 0, 0.2); // 待机状态 - 黄色背景
          color: #ffb300;
        }

        &.offline {
          background: rgba(128, 128, 128, 0.2); // 离线状态 - 灰色背景
          color: #808080;
        }
      }
    }
  }
}

// 添加或修改样式
.chart-title {
  height: 40px;
  padding: 0 20px;
  font-size: 17px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between; // 使状态标签靠右

  .status-tag {
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    min-width: 48px;
    text-align: center;
    margin-top: 3px;
    margin-left: 20px; // 与左边文字保持固定间距
    // 移除 margin-right 和 margin-left: auto

    &.normal {
      background: #20b84e;
      color: #ffffff;
    }

    &.warning {
      background: #ff2b2b;
      color: #ffffff;
    }

    &.waiting {
      background: #ffb300;
      color: #ffffff;
    }

    &.offline {
      background: #808080;
      color: #ffffff;
    }
  }
}

// 基础样式，作为所有状态下的标准样式
.health-score {
  .score-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: calc(100% - 40px);
    padding: 20px;

    .score-circle {
      width: 180px !important;
      height: 180px !important;
    }

    .score-details {
      width: 100%;
      text-align: center;
      margin-top: 10px !important;  // 固定的顶部间距

      .detail-item {
        font-size: 16px;
        line-height: 1.6;
        color: rgba(255, 255, 255, 0.9);
      }
    }
  }
}

// 全屏时只修改间距
.fullscreen-mode {
  .health-score {
    .score-content {
      .score-circle {
        margin: 0 auto !important;  // 全屏时增加底部间距
      }

      .score-details {
        margin-top: 25px !important;  // 全屏时增加顶部间距
      }
    }
  }
}

// 基础样式保持不变
.health-score {
  .score-content {
    .score-circle {
      width: 180px !important;
      height: 180px !important;
    }
  }
}

// 全屏时修改尺寸和间距
.fullscreen-mode {
  .health-score {
    .score-content {

      .score-circle {
        width: 300px;
        height: 300px;

      }

      .score-details {
        top: 40px;  // 通过相对定位向下移动文字
        width: 100%;
        text-align: center;

        .detail-item {
          font-size: 16px;
          margin-top: 30px;
          color: rgba(255, 255, 255, 0.9);
        }
      }
    }
  }
}

// 其他浏览器全屏样式
:fullscreen,
:-webkit-full-screen,
:-moz-full-screen,
:-ms-fullscreen {
  @extend .fullscreen-mode;
}

// 全屏时修改尺寸和位置
.fullscreen-mode {
  .health-score {
    .score-content {
      position: relative;  // 添加相对定位作为参考

      .score-circle {
        width: 300px;
        height: 300px;
        position: relative;   // 添加相对定位
        // left: -40px;         // 向左移动水波图
        margin: 0 auto;      // 保持其他方向的间距
      }

      .score-details {
        top: 40px;
        width: 100%;
        text-align: center;

        .detail-item {
          font-size: 16px;
          margin-top: 30px;

          color: rgba(255, 255, 255, 0.9);
        }
      }
    }
  }
}

/* 全屏模式下的按钮样式调整 */
.fullscreen-mode {
  .center-module {
    .workshop-buttons {
      top: 30px;
      left: 50px; /* 调整左侧距离 */

      .switch-buttons {
        .switch-btn {
          padding: 4px 12px; // 全屏模式下稍微大一点
          font-size: 14px; // 全屏模式下稍微大一点
          min-width: 70px; // 全屏模式下稍微宽一点
        }
      }
    }
  }
}

/* 右下加速度模块 */
.right-bottom-module {
  display: flex;
  grid-column: 2 / span 2;
  grid-row: 2;
  height: 100%;

  .acceleration-chart {
    width: 100%; /* 修改为100%宽度，占满整个区域 */
    height: 100%;
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 10px;
    display: flex;
    flex-direction: column;

    #accelerationChart {
      flex: 1;
      min-height: 200px;
      width: 100% !important;
      height: 100% !important; /* Changed from calc(100% - 10px) */
      /* padding-bottom: 10px; */ /* Removed padding-bottom */
    }
  }

}

.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 16px;
  color: #8f9bb3;
}

.no-data-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

  i {
    font-size: 48px;
    margin-bottom: 10px;
  }
}

/* 全屏模式下的样式调整 */
@mixin fullscreen-styles {
  // ... 其他全屏样式 ...

  .right-bottom-module {
    .acceleration-chart {
      // 标题样式
      .chart-title {
        height: 40px; // 调整标题高度
        font-size: 20px; // 调整标题字体大小
        margin-bottom: 5px; // 调整标题底部间距
      }

      // 图表容器样式
      .chart-container {
        height: calc(100% - 15px); // 调整容器高度
        padding: 10px 0 20px 0; // 增加底部内边距为20px

        #accelerationChart {
          // 这里可以通过CSS变换调整图表的大小和位置
          transform: scaleY(1.1); // Y轴方向放大
          transform-origin: center center; // 从中心点开始变换
          height: calc(100% - 10px) !important; // 底部预留10px空间
        }
      }
    }
  }
}

// 应用全屏样式到各个浏览器
:fullscreen {
  @include fullscreen-styles;
}

:-webkit-full-screen {
  @include fullscreen-styles;
}

:-moz-full-screen {
  @include fullscreen-styles;
}

:-ms-fullscreen {
  @include fullscreen-styles;
}

// 对应类全屏模式
.fullscreen-mode {
  @include fullscreen-styles;
}

/* 调整加速度图表标题和按钮样式 */
.acceleration-chart {
  .chart-title {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 40px;
    position: relative;

    /* 添加标题文本样式 */
    .title-text {
      font-size: 17px;
      color: #fff;
      margin-right: 20px; /* 确保标题和控件之间有空间 */
      white-space: nowrap; /* 防止标题换行 */
    }

    /* 左侧装饰条的位置调整 */
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 3px;
      height: 16px;
      background: #ff9900;
      border-radius: 0 2px 2px 0;
    }

    .chart-controls {
      display: flex;
      align-items: center;
      gap: 10px; /* 减少控件之间的间距 */
      flex-wrap: nowrap; /* 防止控件换行 */
      flex: 1; /* 占据剩余空间 */
      justify-content: flex-start; /* 从左向右排列 */
      overflow-x: auto; /* 当控件太多时允许横向滚动 */
      padding-bottom: 5px; /* 留出滚动条空间 */

      /* 隐藏滚动条但保留功能 */
      &::-webkit-scrollbar {
        height: 2px;
      }

      &::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.1);
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
      }

      .status-tag {
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 12px;
        min-width: auto; /* 移除最小宽度限制 */
        text-align: center;
        white-space: nowrap; /* 防止文字换行 */

        &.normal {
          background: #20b84e;
          color: #ffffff;
        }

        &.warning {
          background: #ff2b2b;
          color: #ffffff;
        }

        &.waiting {
          background: #ffb300;
          color: #ffffff;
        }

        &.offline {
          background: #808080;
          color: #ffffff;
        }
      }

      /* 安装位置下拉选择器样式 */
      .position-dropdown {
        margin-right: 5px;

        .el-dropdown-link {
          display: inline-block;
          padding: 2px 10px;
          border: 1px solid rgba(255, 255, 255, 0.6);
          border-radius: 4px;
          background: transparent;
          color: rgba(255, 255, 255, 0.6);
          cursor: pointer;
          font-size: 12px;
          white-space: nowrap;
          transition: all 0.3s ease;

          &:hover {
            border-color: #fff;
            color: #fff;
            background: rgba(255, 255, 255, 0.1);
          }
        }
      }

      /* 按钮组样式 */
      .switch-buttons {
        display: flex;
        gap: 5px; /* 减小按钮间距 */

        &.position-buttons {
          margin-right: 5px; /* 在位置按钮和类型按钮之间添加间距 */
        }

        .switch-btn {
          padding: 2px 10px; /* 减小内边距 */
          border: 1px solid rgba(255, 255, 255, 0.6);
          border-radius: 4px;
          background: transparent;
          color: rgba(255, 255, 255, 0.6);
          cursor: pointer;
          font-size: 12px;
          transition: all 0.3s ease;
          min-width: auto; /* 移除最小宽度限制 */
          max-width: none; /* 移除最大宽度限制 */
          text-align: center;
          white-space: nowrap; /* 防止按钮文字换行 */

          &:hover {
            border-color: #fff;
            color: #fff;
          }

          &.active {
            background: rgba(255, 255, 255, 0.1);
            border-color: #fff;
            color: #fff;
          }
        }
      }
    }
  }
}

/* Element UI 下拉菜单样式覆盖 */
.el-dropdown-menu {
  background: rgba(3, 12, 49, 0.95) !important;
  border: 1px solid rgba(28, 89, 156, 0.5) !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3) !important;

  .el-dropdown-menu__item {
    color: rgba(255, 255, 255, 0.6) !important;
    font-size: 12px !important;
    padding: 5px 15px !important;

    &:hover {
      background-color: rgba(255, 255, 255, 0.1) !important;
      color: #fff !important;
    }

    &.active-position {
      background-color: rgba(0, 160, 233, 0.2) !important;
      color: #fff !important;

      &::before {
        content: '✓ ';
        color: #00a0e9;
      }
    }
  }
}

// 全屏模式下的下拉菜单样式
:fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen, .fullscreen-mode {
  .el-dropdown-menu {
    background: rgba(3, 12, 49, 0.95) !important;
    border: 1px solid rgba(28, 89, 156, 0.7) !important;

    .el-dropdown-menu__item {
      font-size: 14px !important;
      padding: 8px 20px !important;
    }
  }
}

/* 全屏模式下调整按钮样式 */
@mixin fullscreen-styles {
  // ... 其他全屏样式保持不变

  .acceleration-chart {
    .chart-title {
      height: 50px; /* 全屏模式下增加标题高度 */

      .title-text {
        font-size: 20px; /* 全屏模式下增大标题字体 */
        margin-right: 30px; /* 全屏模式下增加标题和控件之间的间距 */
      }

      .chart-controls {
        gap: 15px; /* 全屏模式下增加控件间距 */

        .status-tag {
          padding: 3px 10px; /* 全屏模式下增大状态标签内边距 */
          font-size: 14px; /* 全屏模式下增大状态标签字体 */
        }

        .position-dropdown {
          .el-dropdown-link {
            padding: 3px 12px; /* 全屏模式下增大按钮内边距 */
            font-size: 14px; /* 全屏模式下增大按钮字体 */
          }
        }

        .switch-buttons {
          gap: 8px; /* 全屏模式下增加按钮间距 */

          .switch-btn {
            padding: 3px 12px; /* 全屏模式下增大按钮内边距 */
            font-size: 14px; /* 全屏模式下增大按钮字体 */
          }
        }
      }
    }
  }

  // 全屏模式下的悬浮提示框样式增强
  .device-item {
    .device-tooltip {
      min-width: 260px; // 全屏模式下增加宽度
      padding: 20px 25px; // 全屏模式下增加内边距
      border-radius: 16px; // 全屏模式下增加圆角

      &::before {
        // 全屏模式下的光效更强
        background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.15), transparent 80%);
      }

      span {
        &:first-child {
          font-size: 22px; // 全屏模式下增大标题字体
          margin-bottom: 12px; // 全屏模式下增加底部间距
          padding-bottom: 12px; // 全屏模式下增加内边距
        }

        &.status-line {
          font-size: 18px; // 全屏模式下增大状态字体

          &::before {
            width: 10px; // 全屏模式下增大状态图标
            height: 10px; // 全屏模式下增大状态图标
            margin-right: 10px; // 全屏模式下增加右侧间距
          }
        }
      }

      // 全屏模式下增加额外信息区域
      &.auto-tooltip-active::after {
        content: attr(data-extra-info);
        display: block;
        margin-top: 10px;
        font-size: 14px;
        opacity: 0.85;
        text-align: center;
        border-top: 1px solid rgba(255, 255, 255, 0.3);
        padding-top: 8px;
      }
    }
  }
}

// 应用全屏样式
:fullscreen, :-webkit-full-screen, :-moz-full-screen, :-ms-fullscreen, .fullscreen-mode {
  @include fullscreen-styles;
}

/* 适应小屏幕 */
@media screen and (max-width: 1366px) {
  .acceleration-chart {
    .chart-title {
      .title-text {
        font-size: 15px; /* 小屏幕下减小标题字体 */
        margin-right: 15px; /* 小屏幕下减小间距 */
      }

      .chart-controls {
        gap: 8px; /* 小屏幕下减小控件间距 */

        .position-dropdown {
          .el-dropdown-link {
            padding: 1px 8px; /* 小屏幕下减小按钮内边距 */
            font-size: 11px; /* 小屏幕下减小按钮字体 */
          }
        }

        .switch-buttons {
          .switch-btn {
            padding: 1px 8px; /* 小屏幕下减小按钮内边距 */
            font-size: 11px; /* 小屏幕下减小按钮字体 */
          }
        }
      }
    }
  }
}

/* 添加图表容器样式 */
.chart-container {
  height: calc(100% - 40px);
  width: 100%;
  overflow: visible; /* 确保变换不会被裁剪 */
  padding-bottom: 10px; /* 底部预留10px空间 */
}

/* 无数据容器样式 */
.no-data-container {
  height: calc(100% - 40px);
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 新增：监测记录滑动动画 */
.log-slide-enter-active,
.log-slide-leave-active {
  transition: all 0.5s cubic-bezier(0.23, 1, 0.32, 1); /* 修改缓动函数 */
}

.log-slide-enter-from /* Vue 3 (or enter for Vue 2) */ {
  opacity: 0;
  transform: scale(0.7) translateY(-30px) rotateX(20deg); /* 增加旋转和调整的进入效果 */
}

.log-slide-leave-to /* Vue 3 (or leave-to for Vue 2) */ {
  opacity: 0;
  transform: scale(0.7) translateY(30px) rotateX(-20deg); /* 增加旋转和调整的离开效果 */
}

.log-slide-leave-active {
  position: absolute; /* 离开时脱离文档流，防止抖动 */
  width: calc(100% - 20px); /* 减去padding的宽度 */
}

.log-slide-move {
  transition: transform 0.8s ease-in-out;
}

/* AI 按钮闪动 */
@keyframes aiPulse {
  0%, 100% { transform: scale(1); opacity: 0.9; }
  50% { transform: scale(1.15); opacity: 1; }
}

.ai-tooltip-btn {
  display: inline-flex;
  margin-top: 8px;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  background: rgba(255,43,43,0.25);
  justify-content: center;
  align-items: center;
  color: #ff2b2b;
  cursor: pointer;
  animation: aiPulse 1.2s infinite;
  i { font-size: 14px; }
}
</style>
